给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
给定 word = “ABCCED”, 返回 true
给定 word = “SEE”, 返回 true
给定 word = “ABCB”, 返回 false
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for i in range(len(board)):
for j in range(len(board[0])):
if self.helper(board, i, j, word, 0):
return True
return False
def helper(self, board, i, j, word, wordIndex):
if wordIndex == len(word):
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[wordIndex] != board[i][j]:
return False
board[i][j] = '#'
found = self.helper(board, i+1, j, word, wordIndex+1)\
or self.helper(board, i, j+1, word, wordIndex+1)\
or self.helper(board, i, j-1, word, wordIndex+1)\
or self.helper(board, i-1, j, word, wordIndex+1)
board[i][j] = word[wordIndex]
return found