Backtracking
Word Search
medium
DESCRIPTION (inspired by Leetcode.com)
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 = [ ['B', 'L', 'C', 'H'], ['D', 'E', 'L', 'T'], ['D', 'A', 'K', 'A'], ] word = "BLEAK"
Output:
True
Example 2:
Input:
board = [ ['B', 'L', 'C', 'H'], ['D', 'E', 'L', 'T'], ['D', 'A', 'K', 'A'], ] word = "BLEED"
Output:
False
Code Editor
Python
Run your code to see results here
Have suggestions or found something wrong?
Explanation
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.
Solution
Solution
Python
from typing import Listclass Solution:def exist(self, board: List[List[str]], word: str) -> bool:rows, cols = len(board), len(board[0])def dfs(r, c, index):if index == len(word):return Trueif r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[index]:return Falsetemp = board[r][c]board[r][c] = "#"found = (dfs(r+1, c, index+1) ordfs(r-1, c, index+1) ordfs(r, c+1, index+1) ordfs(r, c-1, index+1))board[r][c] = tempreturn found# initialize depth-first search from# each of the cells that have the same first# letter as wordfor row in range(rows):for col in range(cols):if board[row][col] == word[0]:if dfs(row, col, 0):return Truereturn False
What is the time complexity of this solution?
where m and n = grid dimensions, L = length of the word
1
O(n * logn)
2
O(m * n * 4^L)
3
O(log n)
4
O(4ⁿ)
Mark as read