Algorithm Day61 - Word Search (lc-79)
🧩 Problem Description
Given an m x n
board of characters and a string word
, return true if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
💬 Examples
Example 1
1 | Input: board = [["A","B","C","E"], |
Example 2
1 | Input: board = [["A","B","C","E"], |
Example 3
1 | Input: board = [["A","B","C","E"], |
💡 Intuition
This is a classic backtracking on a grid problem.
- Try to start from every cell that matches
word[0]
. - From each start, run DFS with index
k
intoword
. - Mark the current cell as visited during the recursion to avoid reuse.
- Backtrack (unmark) when returning.
A tiny optimization: early-exit if remaining occurrences of a letter are impossible (optional).
🔢 Java Code (Backtracking + In-place Visited)
1 | class Solution { |
⏱ Complexity Analysis
Let L = word.length
, m x n = board size
.
- Time: O(m × n × 4^L) in the worst case (tight upper bound). Pruning from mismatches helps in practice.
- Space: O(L) recursion depth; in-place marking avoids extra visited arrays.
✍️ Summary
- Backtracking with DFS from any matching start cell.
- Use in-place marking to avoid revisiting the same cell in a path.
- Return
true
immediately whenk == L
.
Related problems
lc-212
— Word Search II (Trie + backtracking)lc-200
— Number of Islandslc-79
variations — diagonal/knight moves (custom)