Word Search
Word Search is a medium Backtracking problem from the Blind 75. The key pattern is grid backtracking, and a good solution runs in O(cells · 3^L) time.
Problem
Determine whether a word can be traced through horizontally or vertically adjacent cells without reusing a cell.
Examples
Example 1
Input
{"board":[["A","B","C"],["D","E","F"]],"word":"BEF"}Output
trueExample 2
Input
{"board":[["D","U","E"],["C","O","L"],["R","E","S"]],"word":"DUEL"}Output
trueExample 3
Input
{"board":[["D","U","E"],["C","O","L"],["R","E","S"]],"word":"CODE"}Output
falseApproach
Start a depth-first search from each matching cell, step to adjacent cells for the next letter, and undo the visited mark when backing out.
| Pattern | Grid backtracking |
|---|---|
| Time | O(cells · 3^L) |
| Space | O(L) |
Watch out for
A cell can be used only once within a single word.