Word Search
Check whether a word can be traced through touching cells of a letter grid, without using a cell twice.
Given a grid of letters boardmnwordtrue
Example 1
Output: true
Example 2
Output: true
Example 3
Output: false
Explanation: after A, B and C, the last B would have to be the B that was already used.
The Idea
Picture a word-search puzzle in a newspaper, except that here the word may bend. You put a finger on the first letter and slide it to a touching cell for each next letter, never jumping and never landing on the same cell twice.
Write each cell as (row, column), counting from 0. In Example 1, ABCCEDtrue
Example 3, ABCBfalse
On the left is the board, with its row and column numbers and the path so far: A, B, C. On the right, under "the choices for ABCB from A at (0, 0)", the search starts at A at (0, 0) and tries its neighbours in a fixed order: down, up, right, left. Down is S, the wrong letter, and up and left are off the grid, so those boxes are dashed: the search goes no further there. Right is B at (0, 1), which matches, and the same four tries start again from that B, in the row labelled "need C".
In the bottom row, the C at (0, 2) needs a B. Three boxes give a wrong letter or leave the grid, and the box "left: B" is marked "on the path". With all four directions failed, the search steps back to the B at (0, 1) and tries its last direction, left, which is the A already on the path.
So the search builds a path one choice at a time and, when a choice leads nowhere, takes that last cell off the path and tries the next direction from the cell before. Growing a path this way and undoing the last step when it fails is called backtracking. No branch from A at (0, 0) reaches the last B, and the other A, at (2, 0), has no B next to it, so ABCBfalse
Solution Approach
Turning that idea into code means settling three things: where a path may start, how a path grows and when it stops, and how to keep a cell from being used twice. One optional check can also rule out some words before any search.
Where a path may start
Where does the word begin? In any cell that holds its first letter, and there is no way to tell in advance which one works. So the search tries every cell in turn, row by row, and stops at the first start that traces the whole word.
In Example 2, SEE
Growing a path and stopping early
What does one step of the search do? It gets a cell and the position in the word that the cell should match, called indexindex + 1index
A slower way would list every path of the word's length in the grid and compare each one with the word. Checking the letter at every step ends a path at its first wrong letter, like the dashed boxes in the picture, so most paths are never built at all.
Keeping a cell from being used twice
How does a step know that a cell is already on the path? While a cell is on the path, the search writes '#''#'
Why put the letter back? A later path may need that cell. Take the word CCBtrue
A separate grid of boolean
An optional check before searching
Can some words be rejected without searching at all? A word with more letters than the board has cells is too long for any path. Counting letters helps too: on the example board, which has one B, a word with two Bs cannot be traced, and ABCB
Java Solution
The two methods existmatch
- First,
goes over every cell with two loops, one for the rowexist and, inside it, one for the columnr . For each cell it callsc to try that cell as the start of the word.match(board, word, 0, r, c) first checks whethermatch equalsindex . If so, every letter has been matched, and it returnsword.length() .true- Next, it returns
if (false ,r ) is off the grid orc is notboard[r][c] .word.charAt(index) - Otherwise the cell matches.
keeps its letter inmatch and writessaved into the cell, so the path cannot come back to it.'#' - Then
calls itself for the four neighbours, down, up, right and left, each withmatch , joined byindex + 1 . The|| stops at the first direction that returns|| , and the result goes intotrue .found - Finally,
writesmatch back into the cell and returnssaved .found returnsexist as soon as one start succeeds, andtrue once every cell has failed.false
The mainCCB
public class WordSearch {
public static boolean exist(char[][] board, String word) {
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[0].length; c++) {
if (match(board, word, 0, r, c)) {
return true;
}
}
}
return false;
}
// Can the letters of word from position index on be traced starting at cell (r, c)?
private static boolean match(char[][] board, String word, int index, int r, int c) {
if (index == word.length()) {
return true; // every letter matched
}
if (r < 0 || c < 0 || r >= board.length || c >= board[0].length
|| board[r][c] != word.charAt(index)) {
return false; // off the grid or wrong letter
}
char saved = board[r][c];
board[r][c] = '#'; // mark the cell as on the path
boolean found = match(board, word, index + 1, r + 1, c) // down
|| match(board, word, index + 1, r - 1, c) // up
|| match(board, word, index + 1, r, c + 1) // right
|| match(board, word, index + 1, r, c - 1); // left
board[r][c] = saved; // take the cell off the path
return found;
}
public static void main(String[] args) {
char[][] board = {
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'}
};
for (String word : new String[] {"ABCCED", "SEE", "ABCB", "CCB", "ABCDEFGHIJKLM"}) {
System.out.println(word + " -> " + exist(board, word));
}
for (char[] row : board) {
System.out.println(new String(row)); // the board after all searches
}
char[][] single = {{'A'}};
System.out.println("A on [A] -> " + exist(single, "A"));
System.out.println("AA on [A] -> " + exist(single, "AA"));
}
}
Running it prints:
ABCCED -> true
SEE -> true
ABCB -> false
CCB -> true
ABCDEFGHIJKLM -> false
ABCE
SFCS
ADEE
A on [A] -> true
AA on [A] -> false
ABCCEDSEEtrueABCBfalseCCB -> trueABCDEFGHIJKLMfalse
The rows ABCESFCSADEE'#'AAAfalse
What if the line board[r][c] = saved;ABCCEDtrueSEECCBfalse#####F######'#'CCBfalse'#'
Complexity
The work is one search from each cell, and each search may branch at every letter of the word. Here L is the length of the word.
- Time: O(m · n · 3L), because each of the m · n cells can start a search, and after the first letter each step has at most three new directions, as the cell it came from holds
.'#' - Space: O(L), because the calls of
still open at any moment follow the current path, at most L + 1 deep, and the marks live in the board itself, so no extra grid is needed.match
To look for many words in the same grid, store them in a trie, a tree of letters where words with the same beginning share a branch. One search then covers them all.