Word Search
DESCRIPTION (credit 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.
EXAMPLES
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
Run your code to see results here
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
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
Complexity Analysis
Time Complexity:
We iterate over each cell once, which takes a total of m * n time. For each cell, we call the dfs function once.
dfs function: Each dfs call makes a total of 4 additional recursive calls (one in each direction), and will have a max depth of L, where L is the length of the input word. So in total, each dfs function call takes O(4L).
This gives us O(m * n * 4L).
Total Complexity: For each of the m * n cells, the dfs function is called, and each dfs call itself takes O(4L) in the worst case (because there are 4 possible directions and up to L recursive calls). Therefore, the overall time complexity is O(m * n * 4L).
Space Complexity: We have to account for the space on the recursive call stack, which can L calls long at the worst case, for a total of O(L).
Loading comments...