Can you spell a word through neighbouring letters in a grid? Try each path, mark the cells you use, and unmark them when you back out.
▼The problem
LeetCode 79 (Medium). Given an m × n grid of letters and a word, return whether the word can be spelled by a path of horizontally or vertically adjacent cells, using each cell at most once.
Example (from the problem statement): the board [[A,B,C,E],[S,F,C,S],[A,D,E,E]]. "ABCCED" → true (across the top, down, then back along the bottom); "ABCB" → false (the only B next to that C is the B already on the path); "SEE" → true (the walkthrough).
def exist(board, word):
R, C = len(board), len(board[0])
lit = set()
def dfs(r, c, k):
if k == len(word): return True
if not (0 <= r < R and 0 <= c < C): return False
if (r, c) in lit or board[r][c] != word[k]: return False
lit.add((r, c)) # light it
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
if dfs(r + dr, c + dc, k + 1): return True
lit.remove((r, c)) # put it out
return False
return any(dfs(r, c, 0) for r in range(R) for c in range(C))TRY IT ON LEETCODE ▶The solution
def exist(board, word):
R, C = len(board), len(board[0])
lit = set()
def dfs(r, c, k):
if k == len(word): return True
if not (0 <= r < R and 0 <= c < C): return False
if (r, c) in lit or board[r][c] != word[k]: return False
lit.add((r, c)) # light it
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
if dfs(r + dr, c + dc, k + 1): return True
lit.remove((r, c)) # put it out
return False
return any(dfs(r, c, 0) for r in range(R) for c in range(C))Transcript
Word Search. You get a grid of letters and a word. Can you spell the word by stepping between neighboring cells, up, down, left or right, using each cell at most once?
In this grid, A, B, C, C, E, D is there: across the top, down, then back along the bottom. But A, B, C, B is not: the only B next to that C is already used.
Brute force tries every path from every cell. With four ways to go at each step, the choices multiply by four per letter: over a thousand for six letters. But most paths fail by the second letter. Stop them early.
Picture a dark dungeon. Stand on a tile with the first letter and light it. Step only onto a neighbor holding the next letter, and light that too. The lit tiles are your path, so none is used twice. At a dead end, put the light out and step back. That's backtracking.
Let's search for S, E, E. The first S has no E beside it, so it goes dark. The next S has an E above. But that E only touches the lit S and a C. Dead end: it goes dark, and we step back to S. Below is another E, then one more to its left. Found it.
In code, a helper takes a cell and how many letters match so far. If that's all of them, return true. If the cell is off the grid, lit, or the wrong letter, return false. Otherwise light it and try the four neighbors. If none works, put the light out and return false. Start from every cell.
For an m by n grid and a word of L letters, any cell can start. After that, each step has at most three new ways to go, since the way back is lit. So the time is m times n times three to the L. The space is order L, the depth of the path.
Light a tile, try its neighbors, step back when you're stuck. That's Word Search.