Word Search (LeetCode 79): Solution and Explanation
Given a grid of letters and a target word, decide whether the word can be spelled by moving between horizontally or vertically adjacent cells. Each cell can be used at most once within a single spelling of the word.
Watch it run step by step
Try your own input and write the code →Intuition
The word could start at any cell, and from each letter it could continue in up to four directions. There is no ordering or structure in the grid to exploit, so some form of exhaustive search is unavoidable. The goal is to make that search systematic and to cut off dead branches as early as possible.
Depth-first search with backtracking fits naturally. From a starting cell, you try to match word[0], then step to a neighbor and try to match word[1], and so on. If a cell is out of bounds, holds the wrong letter, or is already part of the current path, that branch dies immediately. If you match all L characters, you are done.
The detail that makes it correct is the visited set. A cell used earlier in the current path cannot be reused, but the same cell is perfectly fine for a different path that starts elsewhere or branches differently. So you add the cell to path before exploring its neighbors and remove it afterward. That undo step is the backtracking, and it is what lets one shared set serve every branch of the search.
Approach: Backtracking DFS from every cell
- Record
ROWSandCOLSand create an empty setpathfor cells used in the current attempt. - Define
dfs(r, c, i), which tries to matchword[i:]starting at cell (r, c). Ifi == len(word), every character matched, so return True. - Return False if the cell is out of bounds, its letter differs from
word[i], or it is already inpath. - Add (r, c) to
path, then try the four neighbors withi + 1, stopping at the first success because of short-circuitor. - Remove (r, c) from
pathbefore returning so other branches can use it. - Call
dfs(r, c, 0)from every cell and return True as soon as one succeeds, or False after trying them all.
Step-by-step example
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
- Start at (0,0), which holds A and matches
word[0]. The downward neighbor S does not match B, and up is out of bounds, so the search tries right. - (0,1) holds B, which matches. From there, down is F (no), up is out of bounds, and right is (0,2) holding C, which matches
word[2]. - From (0,2), moving down reaches (1,2), which holds C and matches
word[3]. - From (1,2), moving down reaches (2,2), which holds E and matches
word[4]. - From (2,2), down is out of bounds, up is (1,2) already in
path, right is E (no), and left is (2,1) holding D, which matchesword[5]. - The next call has
iequal to 6, the length of the word, so it returns True and the whole search succeeds.
Code: Python, Java, C++
1class Solution:
2 def exist(self, board: List[List[str]], word: str) -> bool:
3 ROWS, COLS = len(board), len(board[0])
4 path = set()
5
6 def dfs(r, c, i):
7 if i == len(word):
8 return True
9 if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
10 word[i] != board[r][c] or (r, c) in path):
11 return False
12
13 path.add((r, c))
14 res = (dfs(r + 1, c, i + 1) or
15 dfs(r - 1, c, i + 1) or
16 dfs(r, c + 1, i + 1) or
17 dfs(r, c - 1, i + 1))
18 path.remove((r, c))
19 return res
20
21 for r in range(ROWS):
22 for c in range(COLS):
23 if dfs(r, c, 0): return True
24 return False1class Solution {
2 public boolean exist(char[][] board, String word) {
3 for (int i = 0; i < board.length; i++) {
4 for (int j = 0; j < board[0].length; j++) {
5 if (dfs(board, word, i, j, 0)) return true;
6 }
7 }
8 return false;
9 }
10
11 private boolean dfs(char[][] board, String word, int i, int j, int k) {
12 if (k == word.length()) return true;
13 if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(k)) return false;
14
15 char tmp = board[i][j];
16 board[i][j] = '/';
17 boolean res = dfs(board, word, i + 1, j, k + 1) ||
18 dfs(board, word, i - 1, j, k + 1) ||
19 dfs(board, word, i, j + 1, k + 1) ||
20 dfs(board, word, i, j - 1, k + 1);
21 board[i][j] = tmp;
22 return res;
23 }
24}1class Solution {
2public:
3 bool exist(vector<vector<char>>& board, string word) {
4 for (int i = 0; i < board.size(); i++) {
5 for (int j = 0; j < board[0].size(); j++) {
6 if (dfs(board, word, i, j, 0)) return true;
7 }
8 }
9 return false;
10 }
11
12 bool dfs(vector<vector<char>>& board, string word, int i, int j, int k) {
13 if (k == word.length()) return true;
14 if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || board[i][j] != word[k]) return false;
15
16 char tmp = board[i][j];
17 board[i][j] = '/';
18 bool res = dfs(board, word, i + 1, j, k + 1) ||
19 dfs(board, word, i - 1, j, k + 1) ||
20 dfs(board, word, i, j + 1, k + 1) ||
21 dfs(board, word, i, j - 1, k + 1);
22 board[i][j] = tmp;
23 return res;
24 }
25};Time and space complexity
O(m × n × 3^L)
Each of the m × n cells can start a search. After the first step, a path never usefully moves back to the cell it came from, so it branches into at most 3 new directions per character, over L characters.
O(L)
The recursion depth and the path set both hold at most L cells, one for each matched character.
Other approaches
In-place marking instead of a set (time O(m × n × 3^L), space O(L))
Temporarily overwrite board[r][c] with a sentinel such as # while it is on the path and restore it afterward. It saves the hashing cost of a set and uses no extra memory beyond the recursion stack.
Pruning with letter counts (time O(m × n × 3^L), space O(L))
Before searching, count letters in the board and fail fast if the word needs more of any letter than exists. If the last letter of the word is rarer than the first, search the reversed word to reduce branching. The worst case is unchanged, but real inputs run much faster.
Common mistakes
- Forgetting to remove the cell from
pathafter exploring it. Then cells stay blocked for later branches and valid words are missed. - Checking
(r, c) in pathbefore the bounds check in a language that indexes the board first, which can cause an index error. - Using a global visited set that is never reset between different starting cells.
- Allowing diagonal moves. Only the four orthogonal neighbors count.
Frequently asked questions
What is the time complexity of Word Search?
It is O(m × n × 3^L), where L is the length of the word. Every cell can start a search, and each step of the path branches into at most three unvisited directions.
Why is backtracking needed in Word Search?
A cell may be used only once per path, but a cell that fails in one path might be needed in another. Marking it while it is in use and unmarking it afterward enforces the rule without blocking other attempts.
How does Word Search II differ?
Word Search II asks for many words at once. Running this search separately for each word is too slow, so the usual solution builds a trie of all words and runs one DFS over the board that follows trie edges.