Word Search
Medium · Backtracking
Jump to codeDetermine whether a nonempty word can be traced in a rectangular character board by horizontal or vertical moves, without using a cell twice in that path.
Examples
Example 1
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]] word = "ABCCED"
Output: true
Example 2
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]] word = "SEE"
Output: true
Constraints
- 1 <= board.length, board[i].length <= 5
- 1 <= word.length <= 10
- board and word consists of only lowercase and uppercase English letters.
Need a hint?
A visited mark belongs to the current path, not to the entire search.
Real backtracking interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Reach a Target Using Each Number At Most OnceJane Street
- Generate Every Ordered Sum Using Ones and TwosGoogle
- Settle debts with minimal transactionsPinterest
Solution approach
Try each cell as a starting point. Reject a mismatched character or an already used cell. Mark the cell, explore neighbors for the next character, and unmark it before returning, including on success. Reaching the last matching character succeeds.
Complexity
O(mn·4·3^(L−1)) loose worst-case time and O(L) path space.
Python reference solution
def exist(board, word):
if not word:
return True
rows, cols = len(board), len(board[0]) if board else 0
def search(row, col, index):
if index == len(word):
return True
if not (0 <= row < rows and 0 <= col < cols) or board[row][col] != word[index]:
return False
char, board[row][col] = board[row][col], '#'
found = any(search(row + dr, col + dc, index + 1)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
board[row][col] = char
return found
return any(search(r, c, 0) for r in range(rows) for c in range(cols))
JavaScript solution
function exist(board, word) {
if (!word.length) return true;
const rows = board.length, cols = rows ? board[0].length : 0;
function search(row, col, index) {
if (index === word.length) return true;
if (row < 0 || row >= rows || col < 0 || col >= cols || board[row][col] !== word[index]) return false;
const c = board[row][col];
board[row][col] = '#';
const found = search(row + 1, col, index + 1) || search(row - 1, col, index + 1)
|| search(row, col + 1, index + 1) || search(row, col - 1, index + 1);
board[row][col] = c;
return found;
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) if (search(row, col, 0)) return true;
}
return false;
}
Java solution
import java.util.*;
class Solution {
public boolean exist(char[][] board, String word) {
if (word.isEmpty()) return true;
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (search(board, word, row, col, 0)) return true;
}
}
return false;
}
private boolean search(char[][] board, String word, int row, int col, int index) {
if (index == word.length()) return true;
if (row < 0 || row >= board.length || col < 0 || col >= board[row].length
|| board[row][col] != word.charAt(index)) return false;
char c = board[row][col];
board[row][col] = '#';
boolean found = search(board, word, row + 1, col, index + 1)
|| search(board, word, row - 1, col, index + 1)
|| search(board, word, row, col + 1, index + 1)
|| search(board, word, row, col - 1, index + 1);
board[row][col] = c;
return found;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool exist(vector<vector<char>> &board, string word) {
if (word.empty()) return true;
int rows = board.size(), cols = rows ? board[0].size() : 0;
function<bool(int, int, int)> search = [&](int row, int col, int index) {
if (index == (int)word.size()) return true;
if (row < 0 || row >= rows || col < 0 || col >= cols || board[row][col] != word[index]) return false;
char c = board[row][col];
board[row][col] = '#';
bool found = search(row + 1, col, index + 1) || search(row - 1, col, index + 1)
|| search(row, col + 1, index + 1) || search(row, col - 1, index + 1);
board[row][col] = c;
return found;
};
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) if (search(row, col, 0)) return true;
}
return false;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
"A",
"B",
"C",
"E"
],
[
"S",
"F",
"C",
"S"
],
[
"A",
"D",
"E",
"E"
]
],
"ABCCED"
]true
[
[
[
"A",
"B",
"C",
"E"
],
[
"S",
"F",
"C",
"S"
],
[
"A",
"D",
"E",
"E"
]
],
"SEE"
]true
[
[
[
"A",
"B",
"C",
"E"
],
[
"S",
"F",
"C",
"S"
],
[
"A",
"D",
"E",
"E"
]
],
"ABCB"
]false
[
[
[
"A"
]
],
"A"
]true
[
[
[
"A"
]
],
"B"
]false
Drafts are saved per language in this browser when storage is available.