CodeArchon

mediumBacktrackingMicrosoftFacebookBloomberg

Grid Letter Trailblazer

A route planner tries to spell a target word by walking neighboring tiles on a letter board without revisiting any cell.

Given a 2-D board and a word, return true if the word exists on the board. The word can be built from letters of sequentially adjacent cells.

Choose approach

A
cur
B
C
E
S
F
C
S
A
D
E
E
1/7
Narrationstep 1 of 7

Match 'A' at (0,0) with word[0].

1def exist(board, word):
2 R, C = len(board), len(board[0])
3 def dfs(r, c, i):
4 if i == len(word): return True
5 if r<0 or r>=R or c<0 or c>=C or board[r][c] != word[i]: return False
6 tmp = board[r][c]; board[r][c] = '#'
7 ok = dfs(r+1,c,i+1) or dfs(r-1,c,i+1) or dfs(r,c+1,i+1) or dfs(r,c-1,i+1)
8 board[r][c] = tmp
9 return ok
10 return any(dfs(r,c,0) for r in range(R) for c in range(C))
Variables
r=0
c=0
i=0
char=A
path=[0,0]

How to think about it

  1. Match path letters sequentially; mismatch or OOB -> return false.
  2. Mark visited cells with '#'; restore after DFS returns.
  3. Short-circuit on first success.

Edge cases to catch in interview

  • Empty word -> trivially true.
  • Word longer than grid cells -> impossible.

Examples

Example 1true
{"grid":[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"word":"ABCCED"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed