Skip to content

Word Search

Check whether a word can be traced through neighboring grid cells, trying paths and undoing dead ends.

MediumBacktracking
Solve on LeetCode

The problem

You get a grid board of letters and a string word. Return true if you can spell word by starting at some cell and moving to a cell directly above, below, left or right of the current one for each next letter. A cell can't be used twice in the same word, and capital and small letters are different.

Input board = [["S", "T", "A"], ["E", "A", "R"], ["N", "O", "W"]], word = "NEAT"

Output true

Start at N in the bottom row, go up to E, right to the middle A, then up to T.

Input board = [["S", "T", "A"], ["E", "A", "R"], ["N", "O", "W"]], word = "TEAR"

Output false

The only T is in the top row, and none of the cells next to it holds an E.

Key constraint: The board has at most 6 by 6 cells and the word at most 15 letters, which is small enough to try paths one by one.

How to spot the pattern

  • You must find a path through a grid that matches a sequence, one step at a time.
  • Cells on the current path are off limits, but only until you back out of that path.

The idea

Try every cell as the start. From a cell that matches the current letter, the rest of the word has to continue from one of its four neighbors, so ask that same question recursively. Mark the cell while it is on the path so the word can't loop back through it, and unmark it when you back out, because a different path may still need it.

Brute force: List every path of the word's length from every cell and compare each one with the word, which keeps extending paths long after the first wrong letter.

Step by step

  1. 1For every cell, start a search for the word there, and return true as soon as one succeeds.
  2. 2In dfs(r, c, i), return true once i equals the length of the word.
  3. 3Return false if the cell is outside the grid or does not hold word[i].
  4. 4Mark the cell as used, then try dfs on its four neighbors with i + 1.
  5. 5Put the letter back in the cell and return whether any neighbor succeeded.

See the pattern move

The backtracking pattern on a small example. Step through it, or press play.

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        rows, cols = len(board), len(board[0])

        def dfs(r: int, c: int, i: int) -> bool:
            # Can word[i:] be spelled starting at cell (r, c)?
            if i == len(word):
                return True
            if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[i]:
                return False
            board[r][c] = "#"  # mark the cell as used on this path
            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]  # undo the mark before backing out
            return found

        for r in range(rows):
            for c in range(cols):
                if dfs(r, c, 0):
                    return True
        return False

Complexity

Time

O(m * n * 3^L)

Space

O(L)

L is the word's length: a search goes at most L deep and, after the first step, has at most 3 new directions; marking the board in place keeps the extra space to the recursion stack.

Watch out for

  • Not restoring the cell after exploring it, so a search from a later start finds it still marked.
  • Skipping the used mark: a word like ABA can then bounce back and forth between the same two cells.
  • Reading board[r][c] before checking that r and c are inside the grid.

Follow-up questions

How can you make the search faster on bigger boards?

Count the letters first and return false if the board lacks enough of any letter in the word. Also, if the word's last letter is rarer on the board than its first, search for the reversed word, so dead ends appear sooner.

What if you must find many words in the same board?

Put all the words in a trie and run one DFS per cell that walks the trie and the grid together. That is Word Search II.

In Hinglish

Har cell se shuru karke dekho. Letter match hua toh cell ko mark karo, chaaron padosiyon mein agla letter dhoondo, aur wapas aate waqt mark hata do.

Related problems