Problem Description
Given an m x n grid of characters (board) and a string (word), determine if the word exists in the grid. The word must be constructed from letters of sequentially adjacent cells (horizontally or vertically) and a cell cannot be used more than once.
Key Insights
- Use Depth-First Search (DFS) to explore each cell in the board as a potential starting point.
- Employ backtracking to mark cells as visited when exploring a path and revert them back when backtracking.
- Check boundary conditions and ensure the current cell’s character matches the corresponding character in the word.
- Given the small grid and word sizes, a recursive solution is both feasible and straightforward.
- Search pruning can be applied by stopping a DFS branch as soon as the current path does not match the prefix of the target word.
Space and Time Complexity
Time Complexity: O(m * n * 3^L), where L is the length of the word (each DFS may branch to at most 3 further cells, excluding the coming cell). Space Complexity: O(L) due to recursion call stack (where L is the word length).
Solution
The solution uses DFS with backtracking to traverse the grid. For each cell, we:
- Check if the cell matches the first character of the word.
- Recursively explore the adjacent cells (up, down, left, right) while marking the current cell as visited.
- If the path does not lead to a complete match, backtrack by resetting the visited cell.
- The DFS stops if all characters in the word have been found in sequence.
The algorithm leverages in-place modifications (or an auxiliary visited array) to avoid revisiting cells while exploring a candidate path.
Code Solutions
Below are code implementations in Python, JavaScript, C++, and Java with explanatory comments.