Skip to content

Word Search

MediumLeetCode #79Time O(m · n · 3^L)Space O(L)

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)

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))
  • 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.
  • 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 returning True too, 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.

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.

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.

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.