Word Search
Medium
Topics
Given an m x n grid of characters board and a string word, return true if the word can be formed from sequentially adjacent (horizontally or vertically) cells, using each cell at most once.
Example 1
The shaded letters spell
ABCCED in order (the small number is the position in the word).Character grid — one row per line.
Input: board = ["ABCE","SFCS","ADEE"], word = "ABCCED" Output: true
Example 2
No path spells
ABCB: a word must be built from side-adjacent letters without reusing a cell, so the answer is false.Input: board = ["ABCE","SFCS","ADEE"], word = "ABCB" Output: false
Constraints
- 1 <= m, n <= 6
- 1 <= word.length <= 15
Editorial — intuition, approach, complexity and pitfalls
Intuition
Try to match the word starting from every cell, walking to neighbours that continue the word. Mark visited cells during a path and unmark on backtrack so they can be reused by other paths.
Approach
- For each cell, DFS matching word[k] against the cell.
- On a match, temporarily blank the cell and recurse into the 4 neighbours for word[k+1].
- Restore the cell after recursing; succeed when k reaches word length.
Dry Run
board A B C E word = "ABCCED"
S F C S
A D E E
(0,0)=A matches word[0]
(0,1)=B matches word[1]
(0,2)=C matches word[2]
(1,2)=C matches word[3]
(2,2)=E matches word[4]
(2,1)=D matches word[5] -> k reached len(word), true
answer true
This path never backtracks, which makes the restore line look decorative. It is
not. `board[r][c] = "#"` marks the cell as in-use so the path cannot reuse it, and
`board[r][c] = tmp` must put it back when the branch fails -- otherwise a cell
consumed by a dead end stays blocked for every later attempt.
The smallest word on this board that shows it is "EED": correct is true, and
without the restore it is false. The first E tried leads nowhere, is left marked,
and the path that would have succeeded can no longer step on it.
The bounds and the character test are both in the same guard at the top of dfs,
which is why the four recursive calls need no checks of their own -- out-of-range
coordinates are rejected on entry rather than before the call.
The `k == len(word)` base case comes FIRST, before the bounds check, and that
matters in exactly one situation: when the completed match has no in-range
neighbour at all. Put the bounds test first and a 1x1 board holding "A" reports
false for the word "A", because all four recursive calls are rejected on
coordinates before anyone notices the word was already finished. On any larger
board some direction stays in range and the base case is still reached.Complexity
- Time — O(m*n*4^L): each start can branch 4 ways up to the word length L.
- Space — O(L): recursion depth.
Common Pitfalls
- Restore the cell on backtrack, or a cell consumed by a dead end stays blocked for every later attempt. The page's own example does not show it, since its path never backtracks;
EEDon the same board does, returning false where the answer is true.
Full Solution — all languages
class Solution:
def exist(self, board, word):
R,C=len(board),len(board[0])
def dfs(r,c,k):
if k==len(word): return True
if r<0 or r>=R or c<0 or c>=C or board[r][c]!=word[k]: return False
tmp=board[r][c]; board[r][c]="#"
found=dfs(r+1,c,k+1) or dfs(r-1,c,k+1) or dfs(r,c+1,k+1) or dfs(r,c-1,k+1)
board[r][c]=tmp
return found
for r in range(R):
for c in range(C):
if dfs(r,c,0): return True
return Falseimport java.util.*;
class Solution {
public boolean exist(char[][] board, String word) {
int R=board.length,C=board[0].length;
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(dfs(board,word,r,c,0))return true;
return false;
}
boolean dfs(char[][] board,String word,int r,int c,int k) {
int R=board.length,C=board[0].length;
if(k==word.length())return true;
if(r<0||r>=R||c<0||c>=C||board[r][c]!=word.charAt(k))return false;
char tmp=board[r][c];
board[r][c]='#';
boolean found=dfs(board,word,r+1,c,k+1)||dfs(board,word,r-1,c,k+1)||dfs(board,word,r,c+1,k+1)||dfs(board,word,r,c-1,k+1);
board[r][c]=tmp;
return found;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool exist(vector<vector<char>>& board, string word) {
int R=board.size(),C=board[0].size();
function<bool(int,int,int)> dfs=[&](int r,int c,int k)->bool {
if(k==(int)word.size())return true;
if(r<0||r>=R||c<0||c>=C||board[r][c]!=word[k])return false;
char tmp=board[r][c];
board[r][c]='#';
bool found=dfs(r+1,c,k+1)||dfs(r-1,c,k+1)||dfs(r,c+1,k+1)||dfs(r,c-1,k+1);
board[r][c]=tmp;
return found;
};
for(int r=0;r<R;r++)for(int c=0;c<C;c++)if(dfs(r,c,0))return true;
return false;
}
};/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/ var exist = function(board, word) {
const R=board.length,C=board[0].length;
function dfs(r,c,k) {
if(k===word.length)return true;
if(r<0||r>=R||c<0||c>=C||board[r][c]!==word[k])return false;
const tmp=board[r][c];
board[r][c]='#';
const found=dfs(r+1,c,k+1)||dfs(r-1,c,k+1)||dfs(r,c+1,k+1)||dfs(r,c-1,k+1);
board[r][c]=tmp;
return found;
}
for(let r=0;r<R;r++)for(let c=0;c<C;c++)if(dfs(r,c,0))return true;
return false;
};