Word Search

Find a word in a 2D grid via DFS with in-place visited marking.

Medium
Time O(m * n * 4^L) Space O(L)
LeetCode
5 min read
backtracking grid

Problem#

Does word exist in the grid as a path of horizontally/vertically adjacent cells, with each cell used at most once?

Examples#

  • board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"true

Constraints#

  • m, n <= 6, L <= 15.

Approach#

DFS from each cell. Mark visited by temporarily mutating the cell (set to ’#’), recurse to neighbors, restore on backtrack.

Solution#

Word Search
class Solution {
public:
bool exist(vector<vector<char>>& b, string word) {
int m = b.size(), n = b[0].size();
function<bool(int,int,int)> dfs = [&](int r, int c, int i) -> bool {
if (i == (int)word.size()) return true;
if (r < 0 || r >= m || c < 0 || c >= n || b[r][c] != word[i]) return false;
char saved = b[r][c];
b[r][c] = '#';
bool found = dfs(r+1,c,i+1) || dfs(r-1,c,i+1) || dfs(r,c+1,i+1) || dfs(r,c-1,i+1);
b[r][c] = saved;
return found;
};
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
if (dfs(r, c, 0)) return true;
return false;
}
};

Editorial#

In-place visited marking avoids a separate visited matrix. Restoring the cell on backtrack is essential — a sibling DFS branch may need to use it. The character mismatch check (b[r][c] != word[i]) prunes aggressively.

Complexity#

  • Time: O(m * n * 4^L).
  • Space: O(L) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.