sagelearnai

Word Search

Difficulty: Medium · Pattern: Backtracking · LeetCode #79

Given a grid of letters and a word, return true if the word can be spelled by a path of horizontally or vertically adjacent cells, using each cell at most once.

Example

text
board = [["C","A","T"],
         ["X","R","S"],
         ["D","O","G"]]
word = "CAR"  →  true     (C → A → R)
word = "CATS" →  true     (C → A → T → S)
word = "DOGS" →  true     (D → O → G → S)
word = "CAC"  →  false    (can't reuse C)

Hints

  1. Try starting the word at every cell.
  2. From a cell matching word[i], recurse into the four neighbors looking for word[i+1].
  3. Mark the cell as used during the recursion and restore it afterwards (backtrack).

Approach

For each cell, run dfs(r, c, i), which returns whether word[i:] can be matched starting at (r, c). Fail if out of bounds or board[r][c] != word[i]. If i is the last index, succeed. Otherwise temporarily overwrite the cell with a marker (so it can't be reused), try the 4 directions, and restore the cell before returning. A quick prune: if the board doesn't contain enough of some letter, return false immediately.

Complexity

Time: O(R·C·3^L) for word length L (3 directions after the first step). Space: O(L) recursion.

Python solution
def exist(board, word):
    R, C = len(board), len(board[0])
    def dfs(r, c, i):
        if r < 0 or c < 0 or r >= R or c >= C or board[r][c] != word[i]:
            return False
        if i == len(word) - 1:
            return True
        tmp, board[r][c] = board[r][c], "#"
        found = (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))
        board[r][c] = tmp
        return found
    return any(dfs(r, c, 0) for r in range(R) for c in range(C))
JavaScript solution
function exist(board, word) {
  const R = board.length, C = board[0].length;
  const dfs = (r, c, i) => {
    if (r < 0 || c < 0 || r >= R || c >= C || board[r][c] !== word[i]) return false;
    if (i === word.length - 1) return true;
    const tmp = board[r][c]; board[r][c] = '#';
    const found = dfs(r + 1, c, i + 1) || dfs(r - 1, c, i + 1) || dfs(r, c + 1, i + 1) || dfs(r, c - 1, i + 1);
    board[r][c] = tmp;
    return found;
  };
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (dfs(r, c, 0)) return true;
  return false;
}