You are given a 2D grid of characters and a target word string. Your task is to determine whether the word can be constructed by following a path through adjacent cells in the grid. Adjacent cells are those connected horizontally or vertically (diagonal connections do not count). Each cell in the grid can only be used once per search path.
Return true if such a path exists, otherwise return false.
m == board.length (number of rows)n == board[i].length (number of columns)1 <= m, n <= 61 <= word.length <= 15board and word consist of only lowercase and uppercase English lettersExample 1:
Input: board = [['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E']], word = "ABCCED" Output: true Explanation: Starting from A at (0,0), we can trace the path A→B→C→C→E→D
Example 2:
Input: board = [['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E']], word = "SEE" Output: true Explanation: Starting from S at (1,0), we can trace the path S→E→E
Example 3:
Input: board = [['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E']], word = "ABCB" Output: false Explanation: No valid path exists because we would need to reuse cell B
Hint 1: Starting Point You need to try starting the search from every cell in the grid that matches the first character of the word. Use nested loops to iterate through all possible starting positions.
Hint 2: Exploration Strategy Use depth-first search (DFS) with backtracking. From each cell, explore all four adjacent directions recursively. Keep track of which cells have been visited in the current path to avoid reusing them.
Hint 3: State Management You can mark cells as visited by temporarily modifying the board (e.g., changing the character to a special marker) and then restoring it when backtracking. Alternatively, use a separate visited set to track coordinates.
Full Solution `` Approach Explanation:
The solution uses depth-first search (DFS) combined with backtracking to explore all possible paths in the grid:
Outer Loop: Iterate through every cell in the grid to find potential starting points (cells matching the first character of the word)
DFS Search: From each starting point, recursively explore all four adjacent directions (up, down, left, right)
- Check if the current cell matches the current character in the word
- Mark the cell as visited to prevent reuse
- Recursively search adjacent cells for the next character
- If a path leads nowhere, backtrack by unmarking the cell
Visited Tracking: We modify the board in-place by temporarily replacing visited cells with a special marker ('#'). After exploring from a cell, we restore its original value to allow other paths to use it
Early Termination: If we successfully match all characters in the word (index reaches word length), return true immediately
Time Complexity: O(m * n * 4^L) where m and n are the grid dimensions and L is the word length. In the worst case, we start DFS from each cell and explore up to 4 directions at each step.
Space Complexity: O(L) for the recursion call stack, where L is the word length.
def exist(board, word):
"""
Search for a word in a 2D grid using DFS with backtracking.
Time Complexity: O(m * n * 4^L) where m,n are grid dimensions and L is word length
Space Complexity: O(L) for recursion stack depth
"""
if not board or not board[0] or not word:
return False
rows, cols = len(board), len(board[0])
def dfs(row, col, index):
"""
DFS helper to search for word starting at board[row][col]
matching from word[index] onwards.
"""
# Base case: we've matched the entire word
if index == len(word):
return True
# Check boundaries and character match
if (row < 0 or row >= rows or
col < 0 or col >= cols or
board[row][col] != word[index]):
return False
# Mark current cell as visited by temporarily changing it
temp = board[row][col]
board[row][col] = '#'
# Explore all four adjacent directions
found = (dfs(row + 1, col, index + 1) or # down
dfs(row - 1, col, index + 1) or # up
dfs(row, col + 1, index + 1) or # right
dfs(row, col - 1, index + 1)) # left
# Backtrack: restore the cell's original value
board[row][col] = temp
return found
# Try starting the search from each cell in the grid
for r in range(rows):
for c in range(cols):
if board[r][c] == word[0]: # Optimization: only start if first char matches
if dfs(r, c, 0):
return True
return False