79. Word Search
Asked at 32Bloomberg77Amazon65Microsoft54Meta43Google42Apple40Faire100Uber79Grammarly67Karat85Mastercard75PayPal74Netflix73Okta71TikTok70Shopee69eBay64Atlassian63Snap62Yahoo61Walmart Labs60Arista Networks60Epic Systems59Morgan Stanley54Zoho52Cisco45Accenture44Oracle41Visa39Salesforce35IBM35Goldman Sachs33
Problem
Decide whether word can be traced on the letter grid board through horizontally or vertically adjacent cells, using each cell at most once.
Example: board = ["ABCE","SFCS","ADEE"]: "ABCCED" → true; "ABCB" → false
Constraints: board up to 6 × 6; word length ≤ 15. Follow-up: prune the search.
DFS from every cell matching word[0]; mark the cell visited (overwrite with #) while it's on the path, restore on return.
Complexity: O(R·C·3^L).
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
R, C = len(board), len(board[0])
def dfs(r, c, i):
if i == len(word):
return True
if not (0 <= r < R and 0 <= c < C) or board[r][c] != word[i]:
return False
board[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)
board[r][c] = word[i]
return found
return any(dfs(r, c, 0) for r in range(R) for c in range(C))
B = [list("ABCE"), list("SFCS"), list("ADEE")]
assert Solution().exist(B, "ABCCED") is True
assert Solution().exist(B, "SEE") is True
assert Solution().exist(B, "ABCB") is False
class Solution {
public boolean exist(char[][] board, String word) {
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++)
if (dfs(board, word, r, c, 0)) return true;
return false;
}
private boolean dfs(char[][] b, String w, int r, int c, int i) {
if (i == w.length()) return true;
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != w.charAt(i)) return false;
b[r][c] = '#';
boolean found = dfs(b, w, r + 1, c, i + 1) || dfs(b, w, r - 1, c, i + 1)
|| dfs(b, w, r, c + 1, i + 1) || dfs(b, w, r, c - 1, i + 1);
b[r][c] = w.charAt(i);
return found;
}
}
func exist(board [][]byte, word string) bool {
R, C := len(board), len(board[0])
var dfs func(r, c, i int) bool
dfs = func(r, c, i int) bool {
if i == len(word) {
return true
}
if r < 0 || r >= R || c < 0 || c >= C || board[r][c] != word[i] {
return false
}
board[r][c] = '#' // mark as used on this path
found := dfs(r+1, c, i+1) || dfs(r-1, c, i+1) || dfs(r, c+1, i+1) || dfs(r, c-1, i+1)
board[r][c] = word[i]
return found
}
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
if dfs(r, c, 0) {
return true
}
}
}
return false
}