Word Search

medium

You're given an m x n grid of letters called board and a target string word. Return true if word can be spelled out by walking through the grid, and false otherwise.

A path may start at any cell. From a cell you may step to a horizontally or vertically adjacent cell — up, down, left, or right, never diagonally. Each step must land on the next letter of word, and no cell may be used more than once within a single path.

Hints

Where could a valid path possibly begin? Only on a cell that already matches the word's first letter.
As you walk the trail, how do you stop yourself from stepping on the same cell twice within one path?
Blank out a cell before you recurse into its neighbors and restore it right after — that's backtracking on a grid.

Common doubts

No — only to horizontally or vertically adjacent cells (up, down, left, right).
No. Each cell is used at most once per path. Different paths are free to reuse cells.
No. It just has to spell word — any leftover cells are ignored.

Interview follow-ups

Prune before searching: if word needs more of some letter than the board holds, return early; and search from the rarer endpoint by reversing word when its last letter is scarcer than its first.
Build a Trie of all the words and DFS the board a single time, walking the Trie in lockstep with the grid instead of restarting per word.

Fun facts

  • The mark-and-restore trick here is the exact same engine that solves mazes, Sudoku, and N-Queens — backtracking is one idea wearing many costumes.
  • Add a Trie and this problem becomes its harder sibling that searches for a whole dictionary of words in one board sweep.

Asked at

AmazonMicrosoftBloombergFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Trace A(0,0) → B(0,1) → C(0,2) → C(1,2) → E(2,2) → D(2,1).
Example 2
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Trace S(1,3) → E(2,3) → E(2,2).
Example 3
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
The only path spelling ABC dead-ends; the second B is never reachable without reusing a cell.
Constraints

- m == board.length - n == board[i].length - 1 <= m, n <= 6 - 1 <= word.length <= 15 - board and word consist of only lowercase and uppercase English letters.

Solve this problem →