Word Search

Medium

Topics
ArrayBacktrackingMatrix

Given an m x n grid of characters board and a string word, return true if the word can be formed from sequentially adjacent (horizontally or vertically) cells, using each cell at most once.

Example 1

0A1B2C3E1SFC4S2AD6E5E0123
The shaded letters spell ABCCED in order (the small number is the position in the word).
Character grid — one row per line.
Input:  board = ["ABCE","SFCS","ADEE"], word = "ABCCED"
Output: true

Example 2

0ABCE1SFCS2ADEE0123
No path spells ABCB: a word must be built from side-adjacent letters without reusing a cell, so the answer is false.
Input:  board = ["ABCE","SFCS","ADEE"], word = "ABCB"
Output: false

Constraints

  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
Editorial — intuition, approach, complexity and pitfalls

Intuition

Try to match the word starting from every cell, walking to neighbours that continue the word. Mark visited cells during a path and unmark on backtrack so they can be reused by other paths.

Approach

  1. For each cell, DFS matching word[k] against the cell.
  2. On a match, temporarily blank the cell and recurse into the 4 neighbours for word[k+1].
  3. Restore the cell after recursing; succeed when k reaches word length.

Dry Run

board  A B C E        word = "ABCCED"
       S F C S
       A D E E
  (0,0)=A matches word[0]
    (0,1)=B matches word[1]
      (0,2)=C matches word[2]
        (1,2)=C matches word[3]
          (2,2)=E matches word[4]
            (2,1)=D matches word[5]  ->  k reached len(word), true
answer true
This path never backtracks, which makes the restore line look decorative. It is
not. `board[r][c] = "#"` marks the cell as in-use so the path cannot reuse it, and
`board[r][c] = tmp` must put it back when the branch fails -- otherwise a cell
consumed by a dead end stays blocked for every later attempt.
The smallest word on this board that shows it is "EED": correct is true, and
without the restore it is false. The first E tried leads nowhere, is left marked,
and the path that would have succeeded can no longer step on it.
The bounds and the character test are both in the same guard at the top of dfs,
which is why the four recursive calls need no checks of their own -- out-of-range
coordinates are rejected on entry rather than before the call.
The `k == len(word)` base case comes FIRST, before the bounds check, and that
matters in exactly one situation: when the completed match has no in-range
neighbour at all. Put the bounds test first and a 1x1 board holding "A" reports
false for the word "A", because all four recursive calls are rejected on
coordinates before anyone notices the word was already finished. On any larger
board some direction stays in range and the base case is still reached.

Complexity

  • Time — O(m*n*4^L): each start can branch 4 ways up to the word length L.
  • Space — O(L): recursion depth.

Common Pitfalls

  • Restore the cell on backtrack, or a cell consumed by a dead end stays blocked for every later attempt. The page's own example does not show it, since its path never backtracks; EED on the same board does, returning false where the answer is true.

Full Solution — all languages

class Solution:
    def exist(self, board, word):
        R,C=len(board),len(board[0])
        def dfs(r,c,k):
            if k==len(word): return True
            if r<0 or r>=R or c<0 or c>=C or board[r][c]!=word[k]: return False
            tmp=board[r][c]; board[r][c]="#"
            found=dfs(r+1,c,k+1) or dfs(r-1,c,k+1) or dfs(r,c+1,k+1) or dfs(r,c-1,k+1)
            board[r][c]=tmp
            return found
        for r in range(R):
            for c in range(C):
                if dfs(r,c,0): return True
        return False
SensAI
Beta
Tap the mic to stop voice mode