给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
1 class Solution: 2 # (x-1,y) 3 # (x,y-1) (x,y) (x,y+1) 4 # (x+1,y) 5 directions= [(0,-1),(-1,0),(0,1),(1,0)] 6 def exist(self, board: List[List[str]], word: str) -> bool: 7 m = len(board) 8 if m == 0: 9 return False 10 n = len(board[0]) 11 12 marked = [[False for _ in range(n)] for _ in range(m)] 13 # 对每一个格子都从头开始搜索 14 for i in range(m): 15 for j in range(n): 16 if self.__search_word(board,word,0,i,j,marked,m,n): 17 return True 18 return False 19 def __search_word(self,board,word,index,start_x,start_y,marked,m,n): 20 # 先写递归终止条件 21 if index == len(word) -1: 22 return board[start_x][start_y] == word[index] 23 # 中间匹配了,再继续搜索 24 if board[start_x][start_y] == word[index]: 25 # 先占住这个位置,搜索不成功的话,要释放掉 26 marked[start_x][start_y] = True 27 for direction in self.directions: 28 new_x = start_x +direction[0] 29 new_y = start_y + direction[1] 30 ## 注意:如果这一次 search word 成功的话,就返回 31 if 0 <= new_x < m and 0 <= new_y < n and not marked[new_x][new_y] and self.__search_word(board,word,index+1,new_x,new_y,marked,m,n): 32 return True 33 marked[start_x][start_y] = False 34 return False