Word search
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Word search checks whether a word can be traced through a grid of letters by moving to neighbouring cells without reusing a cell. You match one letter, move to a neighbour for the next, and step back when stuck. It is the standard pattern for hunting a sequence through a grid.
Practical use cases
- Web app: Word puzzle game validation. A Boggle-style game on a website lets players drag across letters to form words. When they release, the code checks whether the word can really be traced through neighbouring tiles without reusing one. Wrong swipes are rejected right away with a shake animation.
- Web app: Crossword helper tool. A puzzle site offers a "find this word" helper for a letter grid. The helper tries each cell as a starting point and follows neighbours that match the next letter. A grid of 100 letters is handled in well under a millisecond, because a trail is dropped the moment the next letter does not match, so the helper never feels slow.
- System: Pattern lock checks. A phone pattern lock treats the 3-by-3 dots as a grid and a pattern as a path through neighbouring dots. Verifying that a drawn pattern is legal uses the same stepwise tracing. Tracing letter by letter and retreating on a mismatch is the same habit that powers many grid puzzles, from crosswords to tile games on your phone.
The story: Hidden Words in the Class Puzzle
Mrs. Sharma gave the class a word search puzzle printed on a small sheet: a 3×3 grid of letters. "Find CAST," she said. "You may move up, down, left or right from one letter to the next, but you may not step on the same square twice."
Zoya found the C at the top-left. She looked around for an A: two neighbours had one, below and to the right. She chose the one below. Then she needed an S next to it, but its neighbours were B and N. No luck! "This A is a dead end," she whispered, and she crossed it out lightly in pencil.
She went back to the C and tried the other A, on its right. Its neighbour was an S. And the S had a T under it. C, A, S, T! Zoya shouted with joy, and Mrs. Sharma noticed that Zoya had actually done choose, explore, un-choose without being told.
In a program, "crossing out lightly" is marking the square as used while we are on it, and rubbing the mark out when we leave. That tiny habit lets the same square serve a different attempt later.
How to spot this problem, and where you need it
You must find out whether a sequence of items can be followed through a grid, moving only to neighbouring cells and never reusing a cell.
Signs you need it
- The input is a grid of characters or values and a target word, and the moves are up, down, left or right from the previous cell.
- The same cell may not be used twice in one attempt, but may be used again in a different attempt.
- A simple scan from left to right cannot work because the word may bend and turn.
Where to use it in a project
- Validating a player move in a letter-grid game such as Boggle or word search.
- Checking if a tag or code can be traced through a board layout in a puzzle or learning app.
The solution
Loop over every cell as a possible starting point. If the cell matches the first letter, mark it as used and look at its four neighbours for the second letter, and so on. If all letters are matched, return success. If a neighbour fails, unmark the current cell and go back to try another direction. Stop as soon as one trail succeeds. Unmarking when you retreat is what makes it backtracking.
Payoff: Before: no way to check swipes except by hand. After: each swipe validated in under a millisecond on a 5-by-5 grid.
Explain it like I am 8
Put your finger on the first letter. Look at the four squares around it for the next letter. Move there and keep going. If you cannot find the next letter, slide your finger back to where you came from and choose another neighbour. Never use the same square twice in one try.
How it works, step by step
- Loop over every square as a possible starting point where the first letter matches.
- For a square and a position
kin the word: if it is outside the grid, already used, or the wrong letter, return false. - If
kis the last position of the word, we are done: return true. - Choose: mark the square as used (for example turn it into
#). - Explore: try the four neighbours for the next position. Stop at the first success.
- Un-choose: restore the original letter, then return the result.
The code in four languages
PHP
<?php
// Does the word appear in the grid, moving to neighbours without reusing a cell?
function wordSearch(array $board, string $word): bool {
$rows = count($board);
$cols = count($board[0]);
$dfs = function (int $r, int $c, int $k) use (&$dfs, &$board, $word, $rows, $cols): bool {
if ($r < 0 || $c < 0 || $r >= $rows || $c >= $cols) return false; // outside
if ($board[$r][$c] !== $word[$k]) return false; // wrong letter or used
if ($k === strlen($word) - 1) return true; // matched the last letter
$saved = $board[$r][$c];
$board[$r][$c] = '#'; // choose: mark used
$found = $dfs($r + 1, $c, $k + 1) || $dfs($r, $c + 1, $k + 1)
|| $dfs($r - 1, $c, $k + 1) || $dfs($r, $c - 1, $k + 1); // explore
$board[$r][$c] = $saved; // un-choose
return $found;
};
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($dfs($r, $c, 0)) return true;
}
}
return false;
}
$board = [['C', 'A', 'S'], ['A', 'N', 'T'], ['B', 'E', 'D']];
echo 'CAST: ' . (wordSearch($board, 'CAST') ? 'found' : 'not found') . "\n";
echo 'CATS: ' . (wordSearch($board, 'CATS') ? 'found' : 'not found') . "\n";JavaScript
// Does the word appear in the grid, moving to neighbours without reusing a cell?
function wordSearch(board, word) {
const rows = board.length, cols = board[0].length;
function dfs(r, c, k) {
if (r < 0 || c < 0 || r >= rows || c >= cols) return false; // outside
if (board[r][c] !== word[k]) return false; // wrong letter or used
if (k === word.length - 1) return true; // matched the last letter
const saved = board[r][c];
board[r][c] = '#'; // choose: mark used
const found = dfs(r + 1, c, k + 1) || dfs(r, c + 1, k + 1)
|| dfs(r - 1, c, k + 1) || dfs(r, c - 1, k + 1); // explore
board[r][c] = saved; // un-choose
return found;
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (dfs(r, c, 0)) return true;
}
}
return false;
}
const board = [['C', 'A', 'S'], ['A', 'N', 'T'], ['B', 'E', 'D']];
console.log('CAST: ' + (wordSearch(board, 'CAST') ? 'found' : 'not found'));
console.log('CATS: ' + (wordSearch(board, 'CATS') ? 'found' : 'not found'));Java
public class Main {
// Does the word appear in the grid, moving to neighbours without reusing a cell?
static boolean wordSearch(char[][] board, String word) {
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[0].length; c++) {
if (dfs(board, word, r, c, 0)) return true;
}
}
return false;
}
static boolean dfs(char[][] board, String word, int r, int c, int k) {
if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return false; // outside
if (board[r][c] != word.charAt(k)) return false; // wrong letter or used
if (k == word.length() - 1) return true; // matched the last letter
char saved = board[r][c];
board[r][c] = '#'; // choose: mark used
boolean found = dfs(board, word, r + 1, c, k + 1) || dfs(board, word, r, c + 1, k + 1)
|| dfs(board, word, r - 1, c, k + 1) || dfs(board, word, r, c - 1, k + 1); // explore
board[r][c] = saved; // un-choose
return found;
}
public static void main(String[] args) {
char[][] board = {{'C', 'A', 'S'}, {'A', 'N', 'T'}, {'B', 'E', 'D'}};
System.out.println("CAST: " + (wordSearch(board, "CAST") ? "found" : "not found"));
System.out.println("CATS: " + (wordSearch(board, "CATS") ? "found" : "not found"));
}
}Go
package main
import "fmt"
// wordSearch: does the word appear in the grid, moving to neighbours without reusing a cell?
func wordSearch(board [][]byte, word string) bool {
rows, cols := len(board), len(board[0])
var dfs func(r, c, k int) bool
dfs = func(r, c, k int) bool {
if r < 0 || c < 0 || r >= rows || c >= cols { // outside
return false
}
if board[r][c] != word[k] { // wrong letter or used
return false
}
if k == len(word)-1 { // matched the last letter
return true
}
saved := board[r][c]
board[r][c] = '#' // choose: mark used
found := dfs(r+1, c, k+1) || dfs(r, c+1, k+1) ||
dfs(r-1, c, k+1) || dfs(r, c-1, k+1) // explore
board[r][c] = saved // un-choose
return found
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if dfs(r, c, 0) {
return true
}
}
}
return false
}
func report(found bool) string {
if found {
return "found"
}
return "not found"
}
func main() {
board := [][]byte{{'C', 'A', 'S'}, {'A', 'N', 'T'}, {'B', 'E', 'D'}}
fmt.Println("CAST:", report(wordSearch(board, "CAST")))
fmt.Println("CATS:", report(wordSearch(board, "CATS")))
}Time: O(m × n × 3^L) · Extra space: O(L). Every start cell may launch a walk of length L, and after the first step there are at most 3 new directions. The recursion depth is only the word length.
Watch out for
- Forgetting to restore the cell after exploring, so later starts see "#" where a letter should be.
- Checking the "last letter" before checking the letter matches.
- Reusing a square in the same attempt (no used mark), which wrongly finds words like "ABA" in a single A.
Quick check
- Why mark a cell with # while exploring?
- To save memory
- To make the grid sorted
- So the same cell is not reused in this attempt
- When must the cell be restored?
- Never
- After exploring all neighbours (un-choose)
- Before the first move
- In the demo grid, is CATS found?
- Yes
- Only diagonally
- No