Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example, Given
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true word = "SEE", -> returns true word = "ABCB", -> returns false
This is a typical DFS + backtracking solution. It compares board[row][col] with word[start]. If they match, change board[row][col] to ‘#’ to mark it as visited. Then move to the next one (i.e. word[start + 1]) and compare it to the current neighbors (doing it by recursion).
Below is my code which is not working. I tried debugging but I feel there is off by one error somewhere which I am not able to track.
class Solution(object):
def exist(self, board, word):
def match(board, word, r, c, index):
if r < 0 or r >= len(board) or c < 0 or c >= len(board[0]) or index < 0 or index > len(word):
return False
if index == len(word):
return True
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for x, y in directions:
tmp = board[r][c]
board[r][c] = "#"
if tmp == word[index] and match(board, word, r+x, r+y, index+1):
return True
board[r][c] = tmp
return False
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if board == word:
return True
if not board and word or board and not word:
return False
for r in range(len(board)):
for c in range(len(board[0])):
if match(board, word, r, c, 0):
return True
return False