79. Word Search
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Backtracking
- Time
- O(M*N*4^L)
- Space
- O(L)
Standard Solution (C++)
SummaryGiven a 2D character grid and a target word, determine whether the word can be formed by traversing adjacent (up/down/left/right) cells in sequence, where each cell may be used at most once per path.
Approach
- For every cell in the grid, attempt to start a DFS that matches the word character by character.
- At each step, if the current cell matches the needed character, temporarily mark it visited (in-place) to prevent reuse, then recurse into all four neighbors.
- If the full word is matched (index reaches
word.size()), propagatetrueback immediately. - On backtrack, restore the cell's original character so other search paths can use it.
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
if (dfs(board, word, 0, r, c))
return true;
return false;
}
private:
// Returns true if word[idx..] can be matched starting from (r, c).
bool dfs(vector<vector<char>>& board, const string& word, int idx, int r, int c) {
if (idx == (int)word.size()) return true; // entire word matched
int m = board.size(), n = board[0].size();
if (r < 0 || r >= m || c < 0 || c >= n) return false; // out of bounds
if (board[r][c] != word[idx]) return false; // char mismatch
// Mark visited in-place to avoid reusing this cell in the current path.
char saved = board[r][c];
board[r][c] = '#';
constexpr int dr[] = {-1, 1, 0, 0};
constexpr int dc[] = { 0, 0, 1, -1};
for (int d = 0; d < 4; ++d)
if (dfs(board, word, idx + 1, r + dr[d], c + dc[d]))
return true;
board[r][c] = saved; // restore on backtrack
return false;
}
};
Time O(M * N * 4^L) where M and N are the grid dimensions and L is the word length — each cell can spawn up to 4 recursive branches L levels deep. Space O(L) for the recursion call stack, where L is the length of the word.
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
bool dfs(vector<vector<char>>& board, const string& word, int wordIdx, int x, int y){
if(wordIdx==word.length()){
return true;
}
if(x<0 || x>=board.size() || y<0 || y>=board[0].size() || board[x][y]!=word[wordIdx]){
return false;
}
char tmp=board[x][y];
board[x][y]='#';
int dx[]={-1, 1, 0, 0};
int dy[]={0, 0, 1, -1};
for(int i=0; i<4; ++i){
if(dfs(board, word, wordIdx+1, x+dx[i], y+dy[i])){
return true;
}
}
board[x][y]=tmp;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int m=board.size();
int n=board[0].size();
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(dfs(board, word, 0, i, j)){
return true;
}
}
}
return false;
}
};
// Time Complexity: O(M*N*4^L), where M is the number of rows, N is the number of columns, and L is the length of the word.
// Space Complexity: O(L), where L is the length of the word.
// The space complexity is due to the recursion stack. Time O(M*N*4^L) Space O(L)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.