Word Search
LeetCode 79 · Medium · solution, intuition & step-by-step walkthrough
Grid DFS with a path-visited set.
This is how I solved Word Search (LeetCode 79), a medium problem from the Grid Search / Backtracking DFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Start a DFS from every cell matching the first letter. Each step moves to a neighbour that matches the next letter and hasn't been used on the current path; un-mark the cell when backtracking.
Approach
- 1
dfs(index, row, col): whole word matched → True.
- 2
Out of bounds, wrong letter or already on the path → False.
- 3
Mark, try four directions, unmark.
How I solved it
Backtracking DFSPythonO(mn·3^L) time
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
def dfs(index,row,col,visited):
if index==len(word):
return True
if row<0 or row>=m or col<0 or col>=n:
return False
if board[row][col]!=word[index]:
return False
if (row,col) in visited:
return False
visited.add((row,col))
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if dfs(index+1,nrow,ncol,visited):
return True
visited.remove((row,col))
return False
for i in range(m):
for j in range(n):
visited = set()
if dfs(0,i,j,visited):
return True
return FalseWord Search — FAQ
What is the intuition behind Word Search?
Start a DFS from every cell matching the first letter. Each step moves to a neighbour that matches the next letter and hasn't been used on the current path; un-mark the cell when backtracking.
How do you solve Word Search (LeetCode 79)?
1. dfs(index, row, col): whole word matched → True. 2. Out of bounds, wrong letter or already on the path → False. 3. Mark, try four directions, unmark.
What is the time and space complexity of Word Search?
Time: O(m · n · 3^L). Space: O(L). (Accepted approach: Backtracking DFS.)
What are common mistakes in Word Search?
Un-mark on the way back so other paths can reuse the cell.