Problem
Given a 2D matrix of characters, determine whether a given word exists in the grid when you may move in any of the 8 directions (up, down, left, right and the 4 diagonals). If the word exists, return the visit-order matrix (an m x n integer matrix where each used cell contains its 1-based step index); if the word is not found, return an empty matrix. When multiple valid paths exist, returning any one valid path is acceptable.
Examples
Example 1
$$ \Huge \begin{array}{|c|c|c|c|} \hline A & B & C & E \\ \hline \colorbox{YellowOrange} S & \colorbox{YellowOrange} F & C & S \\ \hline \colorbox{YellowOrange} A & D & \colorbox{YellowOrange} E & E \\ \hline \end{array}
\implies \Huge \begin{array}{|c|c|c|c|} \hline 0 & 0 & 0 & 0 \\ \hline 1 & 3 & 0 & 0 \\ \hline 2 & 0 & 4 & 0 \\ \hline \end{array} $$
| |
Example 2
$$ \Huge \begin{array}{|c|c|c|c|} \hline \colorbox{YellowOrange} k & \colorbox{YellowOrange} 5 & x & c \\ \hline a & \colorbox{YellowOrange} k & 5 & k \\ \hline \colorbox{YellowOrange} c & x & k & x \\ \hline x & c & x & x \\ \hline \end{array}
\implies
\Huge \begin{array}{|c|c|c|c|} \hline 1 & 2 & 0 & 0 \\ \hline 0 & 3 & 0 & 0 \\ \hline 4 & 0 & 0 & 0 \\ \hline 0 & 0 & 0 & 0 \\ \hline \end{array} $$
| |
Example 3
| |
Solution
Method 1 - Backtracking (8-direction, print path)
Intuition
This is a standard DFS/backtracking problem; allowing 8-direction moves only enlarges the neighbor set. We search from every cell and track visited cells. To print the path, we record the visit order in a solution matrix and undo the marks on backtrack.
Approach
- Create a
solutionmatrix of the same dimensions asboard, initialized to zeros. Use astepcounter starting at 1. - Try each cell in the board as a starting point.
- From a cell, perform DFS: if the current character matches
word[idx]and the cell is unused, setsolution[r][c] = stepand increment step. - If
idx == len(word) - 1the full word is matched: return the currentsolutionmatrix (which contains 1-based visit indices). - Otherwise, recurse into all 8 neighbors (dx,dy pairs). If any recursion returns
true, propagatetrueupwards. - If none succeed, undo the mark (
solution[r][c] = 0and decrementstep) and continue searching other starts. - If all starts fail, return
false.
State Definition
solution[r][c]— integer step index (1-based) when cell(r,c)is used in the current candidate path;0means unused.
Code
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(m * n * 8^L)– Letm x nbe board dimensions andLthe word length. From each start we may explore up to 8 neighbors per character, yielding8^Lpossibilities; repeated form*nstarting cells. - 🧺 Space complexity:
O(L + m * n)– recursion stackO(L)plussolutionmatrixO(m*n)used for printing the path.