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.
We can solve this problem using a backtracking approach. The idea is to try to find the target word one character at a time using depth-first search.
We'll iterate over each cell in the grid. If any of the letters in these cells are the same as the first letter of our target word, then we can initialize our depth-first search from that cell.
Depth-First Search Function
To perform our depth-first search, we'll create a helper function dfs. This function will take in r and c, which represent the coordinates of the current cell we are looking at, and index, which represents the index within word that we are searching for.
This function checks if the current cell is equal to the letter we are currently searching for. If so, it makes recursive calls to explore each of its 4 neighbors (in the N, W, S, E) directions to look for the next letter in word.
If it isn't, (or the cell is not in the bounds of the grid), then it returns False immediately.
The base case is when index == len(word), which happens when we have found the target word in our grid, so we can return True.
Keeping Track of Visited Cells
Because our grid is a graph, we have to keep track of visited cells in our current word path to avoid an infinite loop.
Instead of keeping a set of visited cells, we can keep track our visited cells by updating the value of the cell to be some placeholder value such as "#". This means that if we ever encounter a cell with "#", then we can return immediately, as we have already visited this cell on our current path.
We just have to make sure that we backtrack appropriately by restoring the value of the cell to its previous (actual letter) value after the recursive calls have finished.
This is important as it "frees" up the cell to be used by another path in the future, if necessary.
if r <0or c <0or r >= rows or c >= cols or board[r][c]!= word[index]:
returnFalse
temp = board[r][c]
board[r][c]="#"
found =(
dfs(r+1, c, index+1)or
dfs(r-1, c, index+1)or
dfs(r, c+1, index+1)or
dfs(r, c-1, index+1)
)
board[r][c]= temp
return found
# initialize depth-first search from
# each of the cells that have the same first
# letter as word
for row inrange(rows):
for col inrange(cols):
if board[row][col]== word[0]:
if dfs(row, col,0):
returnTrue
returnFalse
Python
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m * n * 4^L) where m and n are the dimensions of the grid and L is the length of the word. We iterate over each cell once (m * n), and for each cell, we call the dfs function which makes 4 recursive calls with a max depth of L, giving us O(4^L) per cell.
Space Complexity: O(L) where L is the length of the word. We need to account for the space on the recursive call stack, which can be L calls deep in the worst case.
Your account is free and you can post anonymously if you choose.