class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
function<bool(int,int,int)> backtrack = [&](int i, int j, int k) {
if(i < 0 || j < 0 || i >= m || j >= n || board[i][j] != word[k]) return false;
if(k == word.size() - 1) return true;
char val = board[i][j];
board[i][j] = '.';
bool res = backtrack(i + 1, j, k + 1)
|| backtrack(i - 1, j, k + 1)
|| backtrack(i, j + 1, k + 1)
|| backtrack(i, j - 1, k + 1);
board[i][j] = val;
return res;
};
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(backtrack(i, j, 0)) return true;
}
}
return false;
}
};Given an m x n grid of characters and a string word, determine whether the word exists in the grid.
Rules:
- The word must be constructed from sequentially adjacent cells (up, down, left, right).
- The same cell cannot be used more than once in a single path.
This is a classic backtracking / DFS on a grid problem.
Key observations:
- Any cell can be a starting point.
- At each step, we try to match the current character and explore 4 directions.
- We must mark the current cell as visited to avoid reuse, then restore it after recursion (backtracking).
- Iterate through every cell in the board as a potential starting point.
- Use DFS (
backtrack) to try matchingword[k]starting from(i, j). - Base cases:
- Out of bounds or character mismatch → return
false - Matched the last character → return
true
- Out of bounds or character mismatch → return
- Mark the cell as visited (temporarily).
- Recursively explore 4 directions.
- Restore the cell value before returning.
- Each recursive call represents choosing one path.
- If a path fails, we undo the choice and try another direction.
- As soon as one valid path matches the full word, we stop early.
O(M × N × 4ᴸ)
M × N: possible starting positions4: branching factor (up, down, left, right)L: length of the word
O(L)
- Maximum recursion depth equals the word length
- Board is modified in-place (no extra visited matrix)
This problem is a textbook example of:
- DFS on a grid
- Backtracking with state restoration
- Early termination once a valid path is found