Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15board and word consists of only lowercase and uppercase English letters.Follow up: Could you use search pruning to make your solution faster with a larger board?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To solve this puzzle, the brute force approach involves exploring every possible path on the board, letter by letter, to see if we can spell out our target word. Since we do not know the correct path ahead of time, we simply try every single starting point and every possible direction from there.
Here's how the algorithm would work step-by-step:
class Solution:n def exist(self, board, word):n row_count = len(board)n col_count = len(board[0])nn def backtrack(row_idx, col_idx, word_idx):n if word_idx == len(word):n return Truenn if row_idx < 0 or row_idx >= row_count or col_idx < 0 or col_idx >= col_count or board[row_idx][col_idx] != word[word_idx]:n return Falsenn # Temporarily mark the current cell as visited by replacing its character with a null byte
current_char = board[row_idx][col_idx]
board[row_idx][col_idx] = '#'nn # Explore all four orthogonal directions to find the next character in the target word sequence
found_match = (n backtrack(row_idx + 1, col_idx, word_idx + 1) orn backtrack(row_idx - 1, col_idx, word_idx + 1) orn backtrack(row_idx, col_idx + 1, word_idx + 1) orn backtrack(row_idx, col_idx - 1, word_idx + 1)
)nn # Restore the cell to its original value so subsequent independent paths can use it
board[row_idx][col_idx] = current_char
return found_matchnn for row_idx in range(row_count):n for col_idx in range(col_count):n if backtrack(row_idx, col_idx, 0):
return Truenn return FalseThe optimal strategy is like playing a word-hunting puzzle by exploring potential paths letter by letter. Whenever we find a matching letter on the board, we carefully venture out in all four directions to find the next letter of our target word, backing up to try a different path if we hit a dead end.
Here's how the algorithm would work step-by-step:
class Solution:
def exist(self, board_grid: list[list[str]], target_word: str) -> bool:
row_count = len(board_grid)
col_count = len(board_grid[0])
def explore_path(current_row: int, current_col: int, word_index: int) -> bool:
if word_index == len(target_word):
return True
if (
current_row < 0 or current_row >= row_count or
current_col < 0 or current_col >= col_count or
board_grid[current_row][current_col] != target_word[word_index]
):
return False
# Temporarily mark the current cell as visited to prevent revisiting it in the same path.
original_character = board_grid[current_row][current_col]
board_grid[current_row][current_col] = '#'
movement_deltas = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for row_delta, col_delta in movement_deltas:
next_row = current_row + row_delta
next_col = current_col + col_delta
if explore_path(next_row, next_col, word_index + 1):
return True
# Restore the original character so other starting paths can use this cell freely.
board_grid[current_row][current_col] = original_character
return False
# Scan the grid to find a valid starting cell matching the first letter of the target word.
for row_index in range(row_count):
for col_index in range(col_count):
if board_grid[row_index][col_index] == target_word[0]:
if explore_path(row_index, col_index, 0):
return True
return False| Case | How to Handle |
|---|---|
| Empty board or empty word string | Return false immediately as a valid path cannot be constructed from or within empty structures. |
| Single cell board matching a single letter word | Return true because the base case correctly verifies the single character match without needing further recursion. |
| Word length exceeds the total number of cells on the board | Return false early by comparing the word length against the total board area before starting the search. |
| Board contains all identical characters | The backtracking visited set prevents reusing the exact same cell index within a single DFS path traversal. |
| Path requires revisiting the same cell in the same sequence | Temporarily mutating the board cell or using a visited tracking mechanism prevents using the same cell more than once. |
| Extremely large grid exceeding recursion stack limits | Iterative DFS or increasing stack depth may be necessary, though standard constraints usually fit within recursion limits. |
| No valid word path exists despite matching starting letters | The backtracking algorithm naturally unwinds and explores all alternative directions before finally returning false. |
| Multiple valid paths exist for the same word | The search short-circuits and returns true upon finding the very first successful complete match. |