Word Search
Medium
BacktrackingMatrixDFS
Problem
Given a 2D board of characters and a target word, return true if it exists by following adjacent cells (up/down/left/right). A cell can't be used twice in one path.
Example 1
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2
Input: word = "SEE"
Output: true
Example 3
Input: word = "ABCB"
Output: false
Constraints
- 1 ≤ m, n ≤ 6
- 1 ≤ word.length ≤ 15
Approach — Backtracking
This is a Backtracking problem. The idea: build candidates one choice at a time and abandon a branch the moment it can't lead to a valid answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: exponential worst case.
Solution code
Python
class Solution:
def exist(self, board, word):
rows, cols = len(board), len(board[0])
g = [list(r) for r in board]
def dfs(r, c, i):
if i == len(word):
return True
if r < 0 or c < 0 or r >= rows or c >= cols or g[r][c] != word[i]:
return False
tmp = g[r][c]
g[r][c] = '#'
found = dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)
g[r][c] = tmp
return found
for r in range(rows):
for c in range(cols):
if dfs(r, c, 0):
return True
return False
Java
class Solution {
public boolean exist(char[][] board, String word) {
int rows = board.length;
int cols = board[0].length;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (dfs(board, word, r, c, 0)) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, String word, int r, int c, int i) {
if (i == word.length()) {
return true;
}
if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) {
return false;
}
if (board[r][c] != word.charAt(i)) {
return false;
}
char tmp = board[r][c];
board[r][c] = '#';
boolean found = dfs(board, word, r + 1, c, i + 1)
|| dfs(board, word, r - 1, c, i + 1)
|| dfs(board, word, r, c + 1, i + 1)
|| dfs(board, word, r, c - 1, i + 1);
board[r][c] = tmp;
return found;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Word Search interactively → ← All solutions