Word Search
The problem
Section titled “The problem”You get a grid of letters and a word. Return true if the word can be spelled by moving
up, down, left or right between adjacent cells, using each cell at most once per path.
board = [[A,B,C,E], [S,F,C,S], [A,D,E,E]]word = "ABCCED" -> true (A -> B -> C -> C -> E -> D)Key insight
Section titled “Key insight”Try every cell as a starting point. From a cell that matches the current letter, try each of the 4 neighbours for the next letter. That is a decision tree where the “choice” is a direction.
The rule “don’t reuse a cell on the same path” needs a visited marker. Instead of a
separate set, overwrite the cell with # (no letter matches it). That is the choose
step. After the four recursive calls, write the original letter back: the un-choose
step. Restoring matters because another path may still need that cell.
The found result is returned only after the restore, so the board is always left intact.
Show solutionHide solution
def exist(board: list[list[str]], word: str) -> bool: rows, cols = len(board), len(board[0])
def backtrack(r: int, c: int, k: int) -> bool: if k == len(word): return True # matched every letter if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[k]: return False # off the grid, wrong letter, or already used ('#') board[r][c] = "#" # choose: mark visited in place found = ( backtrack(r + 1, c, k + 1) or backtrack(r - 1, c, k + 1) or backtrack(r, c + 1, k + 1) or backtrack(r, c - 1, k + 1) ) # explore board[r][c] = word[k] # un-choose: restore on the way out return found
return any(backtrack(r, c, 0) for r in range(rows) for c in range(cols))export function exist(board: string[][], word: string): boolean { const rows = board.length; const cols = board[0].length;
function backtrack(r: number, c: number, k: number): boolean { if (k === word.length) return true; // matched every letter if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[k]) { return false; // off the grid, wrong letter, or already used ('#') } board[r][c] = '#'; // choose: mark visited in place const found = backtrack(r + 1, c, k + 1) || backtrack(r - 1, c, k + 1) || backtrack(r, c + 1, k + 1) || backtrack(r, c - 1, k + 1); // explore board[r][c] = word[k]; // un-choose: restore on the way out return found; }
for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { if (backtrack(r, c, 0)) return true; } } return false;}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 (backtrack(board, word, r, c, 0)) return true; } } return false; }
private boolean backtrack(char[][] board, String word, int r, int c, int k) { if (k == word.length()) return true; // matched every letter if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] != word.charAt(k)) { return false; // off the grid, wrong letter, or already used ('#') } board[r][c] = '#'; // choose: mark visited in place boolean found = backtrack(board, word, r + 1, c, k + 1) || backtrack(board, word, r - 1, c, k + 1) || backtrack(board, word, r, c + 1, k + 1) || backtrack(board, word, r, c - 1, k + 1); // explore board[r][c] = word.charAt(k); // un-choose: restore on the way out return found; }}Complexity
Section titled “Complexity”- Time: O(m · n · 3^L) — m × n starting cells; the path is up to L letters long. After the first step, one of the 4 neighbours is the cell you came from (marked), leaving at most 3 branches.
- Space: O(L) — the recursion goes at most L deep. The visited marking is done in place, so there is no extra grid.
Watch out for
Section titled “Watch out for”- Restore the cell on every exit. If a failed branch returns without writing the letter
back, the cell stays
#and later paths and starts that need it wrongly fail. Restore before returningTruetoo, so the caller gets its board back intact. - Check the bounds before indexing. Test row and column first, then compare the letter.
- Check
k == len(word)first. It must come before the bounds check, or a word that ends at the board’s edge is wrongly rejected.
Variations
Section titled “Variations”Word Search II (LeetCode 212)
Section titled “Word Search II (LeetCode 212)”Find all words from a list that appear in the grid. The trick: put the words in a trie and run one DFS that walks the trie as it walks the grid. A branch dies when no word has that prefix, so you search all words at once.
Number of Islands (LeetCode 200)
Section titled “Number of Islands (LeetCode 200)”Count connected groups of land cells. The trick: the same in-place marking, but you never restore: once a cell is visited it is done for good, so this is plain DFS, not backtracking.
Palindrome Partitioning (LeetCode 131)
Section titled “Palindrome Partitioning (LeetCode 131)”Split a string so every piece is a palindrome; return all splits. The trick: the choice is where to cut next. Try each prefix that is a palindrome, recurse on the rest, and record when the whole string is consumed.