Skip to main content
41

Word Search

Mediumbacktrackingmatrix

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:BacktrackingRead the beginner guide

Given an m x n grid of letters board and a string word, return true if word can be traced on the board, and false otherwise.

Understand the problem

  • To trace a word, start on a cell holding its first letter, then step to a neighboring cell for each next letter, in order.
  • Neighbors are the cells directly up, down, left or right (not diagonal).
  • The same cell can't be used twice in the word.
  • Letters are case-sensitive: a and A are different.
text
board = [["A","B","C","E"],
         ["S","F","C","S"],
         ["A","D","E","E"]]

Example 1

text
word = "ABCCED"  →  true

A (top-left) → B (right) → C (right) → C (down) → E (down) → D (left).

Example 2

text
word = "SEE"  →  true

S (row 1, last column) → E (down) → E (left).

Example 3

text
word = "ABCB"  →  false

A → B → C works, but the only B next to that C is the one already used.

Constraints

  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • Letters are uppercase and lowercase English letters.

Note

Follow-up: before searching, can you quickly rule out boards that can't possibly contain the word?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    From every cell, run a depth-first search that matches the word letter by letter, marking cells as used on the way in and restoring them on the way out.

    The key insight

    Tracing a word is a series of choices: from the current cell, which neighbor do I step to next? That's a job for backtracking: try a choice, explore everything that follows, then undo it and try the next one.

    dfs(r, c, i) answers: can the rest of the word, word[i..], be traced starting at cell (r, c)?

    1. Fail fast: if (r, c) is off the board, or the cell's letter isn't word[i], return false. (A used cell holds #, which never matches, so this also blocks reuse.)
    2. Done: if i is the last index, the whole word matched: return true.
    3. Mark the cell as used: board[r][c] = '#'.
    4. Explore the four neighbors with i + 1. If any returns true, so do we.
    5. Restore the letter. This is the "undo" step: a different path might pass through this cell later.

    Writing # into the board itself saves us from keeping a separate "visited" set.

    Step by step

    word = "SEE" on the board from the description:

    CallCell letterExpectedWhat happens
    start at (0, 0)ASno match, try the next start
    ...(cells that aren't S fail immediately)
    start at (1, 0)SSmatch! mark it, try neighbors for E
    neighbors of (1, 0)A, A, FEnone match: restore (1, 0), back up
    start at (1, 3)SSmatch! mark it
    down to (2, 3)EEmatch! mark it
    left to (2, 2)EElast letter → true

    The code

    The reference solution is below, with comments on every important line.

    It also includes the follow-up's pruning, before the search starts:

    • Count the letters. If the board has fewer copies of some letter than the word needs, return false right away.
    • Search from the rarer end. If the word's first letter is more common on the board than its last letter, search for the reversed word instead (a word can be traced forward exactly when its reverse can be). Fewer starting cells means a much smaller search. For example, on Example 1 the board has two As but only one D, so the solution actually searches for DECCBA.

    How fast is it?

    With m × n cells and L = the word's length:

    • Time: O(m · n · 3^L) in the worst case: from each start, every later step has at most 3 new directions (you can't step back onto the cell you came from).
    • Memory: O(L) for the recursion.

    Common mistakes

    • Forgetting to restore the cell. Then a failed path leaves # marks behind, and later searches wrongly fail.
    • Restoring the wrong letter. Save the original letter (or use word[i], which is the same since it matched).
    • Allowing diagonal moves. Only up, down, left and right.
    • Checking i === word.length instead of the last index, then stepping into a neighbor that may be off the board. Either works if done carefully, but checking the last index avoids an extra call.

    Going deeper

    Word Search II asks the same question for up to 30,000 words at once. Running this search for each word is too slow there; a trie lets one search find all the words together.

    Reference solution

    js
    /**
     * @param {string[][]} board
     * @param {string} word
     * @return {boolean}
     */
    export default function exist(board, word) {
      const rows = board.length
      const cols = board[0].length
    
      // Pruning 1: if the board doesn't have enough of some letter, give up right away.
      const available = new Map()
      for (const row of board)
        for (const char of row) available.set(char, (available.get(char) ?? 0) + 1)
      const needed = new Map()
      for (const char of word) needed.set(char, (needed.get(char) ?? 0) + 1)
      for (const [char, count] of needed) if ((available.get(char) ?? 0) < count) return false
      // Pruning 2: search from the rarer end. A word can be traced exactly when its reverse can,
      // and fewer starting cells means a much smaller search.
      if ((available.get(word[0]) ?? 0) > (available.get(word.at(-1)) ?? 0)) {
        word = [...word].reverse().join('')
      }
    
      // Can word[i..] be traced starting at cell (r, c)?
      function dfs(r, c, i) {
        if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[i]) return false // off the board, used, or wrong letter
        if (i === word.length - 1) return true // matched the last letter
        board[r][c] = '#' // mark as used, so this path can't step on it again
        // Try all four neighbors for the next letter.
        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] = word[i] // backtrack: give the letter back for other paths
        return found
      }
    
      // The word may start at any cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) if (dfs(r, c, 0)) return true
      }
      return false
    }
    ts
    export default function exist(board: string[][], word: string): boolean {
      const rows = board.length
      const cols = board[0].length
    
      // Pruning 1: if the board doesn't have enough of some letter, give up right away.
      const available = new Map<string, number>()
      for (const row of board)
        for (const char of row) available.set(char, (available.get(char) ?? 0) + 1)
      const needed = new Map<string, number>()
      for (const char of word) needed.set(char, (needed.get(char) ?? 0) + 1)
      for (const [char, count] of needed) if ((available.get(char) ?? 0) < count) return false
      // Pruning 2: search from the rarer end. A word can be traced exactly when its reverse can,
      // and fewer starting cells means a much smaller search.
      if ((available.get(word[0]) ?? 0) > (available.get(word.at(-1)!) ?? 0)) {
        word = [...word].reverse().join('')
      }
    
      // Can word[i..] be traced starting at cell (r, c)?
      function dfs(r: number, c: number, i: number): boolean {
        if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[i]) return false // off the board, used, or wrong letter
        if (i === word.length - 1) return true // matched the last letter
        board[r][c] = '#' // mark as used, so this path can't step on it again
        // Try all four neighbors for the next letter.
        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] = word[i] // backtrack: give the letter back for other paths
        return found
      }
    
      // The word may start at any cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) if (dfs(r, c, 0)) return true
      }
      return false
    }
    python
    from collections import Counter
    
    
    def exist(board: list[list[str]], word: str) -> bool:
        rows, cols = len(board), len(board[0])
    
        # Pruning 1: if the board doesn't have enough of some letter, give up right away.
        available = Counter(char for row in board for char in row)
        if any(available[char] < count for char, count in Counter(word).items()):
            return False
        # Pruning 2: search from the rarer end. A word can be traced exactly when its reverse can,
        # and fewer starting cells means a much smaller search.
        if available[word[0]] > available[word[-1]]:
            word = word[::-1]
    
        # Can word[i:] be traced starting at cell (r, c)?
        def dfs(r: int, c: int, i: int) -> bool:
            if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]:
                return False  # off the board, used, or wrong letter
            if i == len(word) - 1:
                return True  # matched the last letter
            board[r][c] = "#"  # mark as used, so this path can't step on it again
            # Try all four neighbors for the next letter.
            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] = word[i]  # backtrack: give the letter back for other paths
            return found
    
        # The word may start at any cell.
        return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))