Word Search
Master this topic with zero to advance depth.
Word Search
Backtracking on 2D Grids
This problem is a classic example of DFS on a grid. We need to find a sequence of adjacent cells that match the characters of a given word.
Core Rules
- Use each cell at most once per word (requires tracking visited cells).
- Move in four directions: Up, Down, Left, Right.
Performance Optimization
To avoid using extra space for a visited array, we can temporarily modify the board with a special character (like '#') to mark a cell as visited, then restore it after recursion (Backtracking).
Find a word in a 2D grid using DFS. Includes visual traversal trace.
Examples
Level I: DFS Backtracking (Visited Set)
Intuition
Try starting at every cell . If it matches word[0], explore its neighbors recursively.
Use a visited set to keep track of used cells in the current path. If we match all characters of the word, return true.
Detailed Dry Run
Dry Run: board=[['A','B'],['C','D']], word="ABD"
| Step | Cell | Char | Path | Action |
| :--- | :---: | :--- | :--- | :--------------- |
| 1 | (0,0) | 'A' | "A" | Match, try neighbors |
| 2 | (0,1) | 'B' | "AB" | Match, try neighbors |
| 3 | (1,1) | 'D' | "ABD"| Match! SUCCESS |
| 4 | (1,0) | 'C' | - | No Match (from A) |Level II: Optimized Backtracking (Frequency Pruning)
Intuition
Before starting DFS, check if the board contains enough characters to form the word.
Count the frequency of each char in the board and the word. If the board has fewer characters than the word for any char, return false immediately. This avoids work in impossible cases.
Detailed Dry Run
word="AAAAA", board has only two 'A's -> Return FALSE immediately.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.