Word Search
Pattern: Word search
Start from every cell that matches the first letter, and grow the match through neighbouring cells, marking each cell used on the current path so it is not reused. Restore the cell when backing out. Stop at the first full match.
The problem
Given a grid of letters and a word, return whether the word can be traced through the grid, moving between cells that
share a side (up, down, left, right), without using any cell twice. For example, with the rows ABCE, SFCS and ADEE,
ABCCED and SEE give true and ABCB gives false (the B would be reused).
The function name exist matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Where can a match start?
- After matching letter
iat a cell, where can letteri + 1be? - How do you stop a path from using a cell twice, without a separate visited grid?
Hints
Brute force, and why it fails
There is no fast general method; every start and path may need trying. The search costs about R × C × 3^L for a word
of length L, since each step has at most 3 new directions.
The key insight
Matching letter by letter prunes almost every path at once, because most neighbours hold the wrong letter. Marking cells in place keeps paths simple at no extra memory.
Dry run
The board rows are ABCE, SFCS and ADEE, and the word is ABCCED. Start at (0, 0), which holds A.
The plan
function match(r, c, i):
if (r, c) is outside or board[r][c] != word[i]: return false
if i == len(word) - 1: return true
saved = board[r][c]; board[r][c] = '#'
found = match(r+1, c, i+1) or match(r-1, c, i+1) or match(r, c+1, i+1) or match(r, c-1, i+1)
board[r][c] = saved
return found
return any match(r, c, 0)
Complexity
- Time
O(R × C × 3^L)- Space
O(L)
Each start explores at most 3^L paths. The recursion is L deep.
Edge cases
- A word of one letter: any matching cell.
- A word longer than the number of cells: false.
- Many equal letters, as in a grid of
As: the search is slow but correct.
I've built my logic, show the code
Java
class Solution {
public 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, r, c, 0)) return true; // try every starting cell
return false;
}
private boolean match(char[][] b, String w, int r, int c, int i) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != w.charAt(i)) return false;
if (i == w.length() - 1) return true; // the whole word matched
char saved = b[r][c];
b[r][c] = '#'; // mark as used on this path
boolean found = match(b, w, r + 1, c, i + 1) || match(b, w, r - 1, c, i + 1)
|| match(b, w, r, c + 1, i + 1) || match(b, w, r, c - 1, i + 1);
b[r][c] = saved; // restore for other paths
return found;
}
}C++
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for (size_t r = 0; r < board.size(); r++)
for (size_t c = 0; c < board[0].size(); c++)
if (match(board, word, static_cast<int>(r), static_cast<int>(c), 0)) return true; // every start
return false;
}
bool match(vector<vector<char>>& b, const string& w, int r, int c, size_t i) {
if (r < 0 || c < 0 || r >= static_cast<int>(b.size()) || c >= static_cast<int>(b[0].size()) || b[r][c] != w[i]) return false;
if (i == w.size() - 1) return true; // the whole word matched
char saved = b[r][c];
b[r][c] = '#'; // mark as used on this path
bool found = match(b, w, r + 1, c, i + 1) || match(b, w, r - 1, c, i + 1)
|| match(b, w, r, c + 1, i + 1) || match(b, w, r, c - 1, i + 1);
b[r][c] = saved; // restore for other paths
return found;
}
};Python
class Solution:
def exist(self, board: list[list[str]], word: str) -> bool:
R, C = len(board), len(board[0])
def match(r: int, c: int, i: int) -> bool:
if not (0 <= r < R and 0 <= c < C) or board[r][c] != word[i]:
return False
if i == len(word) - 1:
return True # the whole word matched
saved, board[r][c] = board[r][c], "#" # mark as used on this path
found = (match(r + 1, c, i + 1) or match(r - 1, c, i + 1)
or match(r, c + 1, i + 1) or match(r, c - 1, i + 1))
board[r][c] = saved # restore for other paths
return found
return any(match(r, c, 0) for r in range(R) for c in range(C))Common mistakes
- Not restoring the cell, which breaks later searches from other starts.
- Allowing the path to step back onto a used cell.
- Checking bounds after reading the cell.