Given an m x n
board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
m
and n
)?We’ll use backtracking to explore all possible paths on the board from each cell to see if they lead to the given word. The key steps in our strategy:
True
.The time complexity of this approach in the worst case is O(m * n * 4^L)
, where m
is the number of rows, n
is the number of columns, and L
is the length of the word. This is because in the worst case, we might explore all 4 directions for each cell of the board.
Here’s the Python code to solve this problem:
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not board or not board[0]:
return False
self.rows = len(board)
self.cols = len(board[0])
self.word = word
self.board = board
for r in range(self.rows):
for c in range(self.cols):
if self._dfs(r, c, 0):
return True
return False
def _dfs(self, r, c, index):
if index == len(self.word):
return True
if r < 0 or r >= self.rows or c < 0 or c >= self.cols or self.board[r][c] != self.word[index]:
return False
# Temporary mark the cell as visited
temp = self.board[r][c]
self.board[r][c] = '#'
# Explore all possible directions
for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
if self._dfs(r + dr, c + dc, index + 1):
return True
# Backtrack and unmark the cell
self.board[r][c] = temp
return False
rows
and cols
) and store the word and the board.r
, c
) in the board._dfs
):
index
matches the length of the word, it means the word has been found.This code efficiently explores all potential ways to form the word while ensuring that no cell is reused more than once in a single path.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?