The "Word Search" problem asks whether a given word can be formed by sequentially adjacent letters on a 2D grid of characters.
A move is valid if it steps horizontally or vertically to a neighboring cell, and each cell can only be used once during a single search path.
For example, if the word is "ABCCED" and the grid is arranged in such a way that this path exists by moving from cell to cell, then the result is true
.
Since the word can start at any cell and proceed in four directions, we must consider every position in the grid as a potential starting point. From each cell, we perform a depth-first search (DFS) to try to build the word, one character at a time.
At every recursive call, we check whether the character at the current grid position matches the corresponding character in the word.
If it doesn't match or if the cell has already been used in the current path, we backtrack.
If it does match, we mark the cell as visited (often by temporarily changing its value to a placeholder like '#'
), and recursively attempt to complete the rest of the word using adjacent cells.
The recursion proceeds until we've either matched the full word or exhausted all valid options from the current path. After exploring all directions from a given cell, we must revert the cell to its original value so that it can be used in other paths.
Before beginning the main logic, we handle edge cases such as an empty grid or a grid with only one character. These special cases help prevent unnecessary computation and ensure correctness when the input is minimal.
In the worst-case scenario, we visit each cell and recursively try up to 4 directions for each character in the word. The time complexity is therefore O(m * n * 3^W), where m and n are the grid dimensions, and W is the length of the word. The 3 arises because after the first move, we can at most go in three remaining directions (we avoid reversing direction).
The space complexity is O(W) for the recursion call stack, where W is the length of the word. We may also use O(m * n) auxiliary space if we track visited cells with a separate matrix, though overwriting characters is a common in-place approach.
This problem is a classic example of grid-based DFS with backtracking. The key idea is to prune invalid paths early and carefully manage cell visitation to avoid revisiting the same location. By attempting all possible paths from every cell, the algorithm guarantees that it finds a solution if one exists, while avoiding redundant or impossible routes.