Word Search
Problem Statement:โ
Given anย m x nย grid of charactersย boardย and a stringย word, returnย trueย ifย wordย exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
-
Example:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
โ Solution: Backtracking (DFS on Grid)โ
class Solution {
public:
// Recursive DFS to match characters in all 4 directions
bool searchNext(vector<vector<char>> &board, string word, int row, int col, int index, int m, int n){
if(index == word.length()) return true;
// Out of bounds or mismatch or visited cell
if(row < 0 || col < 0 || row >= m || col >= n || board[row][col] != word[index] || board[row][col] == '!'){
return false;
}
char c = board[row][col]; // Save the current character
board[row][col] = '!'; // Mark as visited
// Explore in all four directions
bool up = searchNext(board, word, row - 1, col, index + 1, m, n);
bool down = searchNext(board, word, row + 1, col, index + 1, m, n);
bool left = searchNext(board, word, row, col - 1, index + 1, m, n);
bool right = searchNext(board, word, row, col + 1, index + 1, m, n);
board[row][col] = c; // Unmark (Backtrack)
return up || down || left || right;
}
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
// Try every cell as a starting point
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == word[0]){
if(searchNext(board, word, i, j, 0, m, n))
return true;
}
}
}
return false;
}
};
๐ How It Worksโ
- We're given a 2D grid
boardand a stringword. - The goal is to check whether
wordcan be formed by starting from any cell and moving up, down, left, or right without revisiting any cell. - The
searchNextfunction is a DFS that:- Checks base case: if
index == word.length()โ word is matched. - Bounds check and visited check (
board[row][col] == '!'). - Temporarily marks current cell as visited by setting it to
'!'. - Tries all 4 directions recursively.
- Backtracks by restoring the cell's original character.
- Checks base case: if
๐งฉ Key Formula / Recurrenceโ
searchNext(row, col, index) =
searchNext(row + 1, col, index + 1) ||
searchNext(row - 1, col, index + 1) ||
searchNext(row, col + 1, index + 1) ||
searchNext(row, col - 1, index + 1)
โฑ๏ธ Time & Space Complexityโ
๐ธ Time Complexity: O(M ร N ร 4^L)โ
Where:
M= number of rows in the boardN= number of columnsL= length of theword
Explanation:
- You try starting from every cell โ
M ร Ncalls. - For each call, you may explore up to 4 directions (up/down/left/right).
- In the worst case, from each step you explore 4 more paths โ up to
4^Lrecursive calls per path.
โ
Total worst-case time = O(M ร N ร 4^L)
๐ธ Space Complexity: O(L)โ
Why?
- The recursion depth is equal to
L(the word length), as each recursive call adds 1 letter. - We do in-place marking (
board[row][col] = '!') to avoid using extra space for a visited matrix.
โ Total space = O(L) for the call stack
โ ๏ธ Edge Casesโ
- Empty grid or empty word โ return
false - Word longer than total grid cells โ can't be matched
- Grid with same repeating letters โ handled via visited marking
๐ก Other Approachesโ
| Approach | Time | Use Case |
|---|---|---|
| Trie + DFS (Word Search II) | O(M ร N ร L ร 4^L) | Optimized for multiple word queries |
| Iterative DFS/BFS | Similar | Harder to implement due to visited tracking |
๐ Related Problemsโ
- Leetcode 79. Word Search โ (this one)
- Leetcode 212. Word Search II ๐ฅ (uses Trie)
- Leetcode 200. Number of Islands
- Leetcode 694. Number of Distinct Islands
Let me know if you want the optimized Trie-based version for multiple word searches (Leetcode 212)!
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.