问题描述
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
思路
思路倒是很简单。用DFS找出来符合条件的即可。不过我可能是老了,竟然不会写DFS了。真的蛋疼。
AC代码
class Solution:
def exist(self, board, word: str) -> bool:
target_word = word[0]
self.height = len(board)
self.width = len(board[0])
self.used = [[False for i in range(self.width)] for i in range(self.height)]
flag = False
for i in range(self.height):
for j in range(self.width):
if board[i][j] == target_word:
self.used[i][j] = True
flag = self.dfs(board,i,j,word[1:])
if flag:
return flag
self.used[i][j] = False # 状态回退
return flag
def dfs(self,board,i,j,word):
if len(word) == 0:
return True
target_search = word[0]
stack = [] # 搜索四个方向。stack暂存结果
if 0<j and not self.used[i][j-1] and board[i][j-1] == target_search:
stack.append((i,j-1))
if j<self.width-1 and not self.used[i][j+1] and board[i][j+1] == target_search:
stack.append((i,j+1))
if 0<i and not self.used[i-1][j] and board[i-1][j] == target_search:
stack.append((i-1,j))
if i<self.height-1 and not self.used[i+1][j] and board[i+1][j] == target_search:
stack.append((i+1,j))
for i in stack:
self.used[i[0]][i[1]] = True
flag = self.dfs(board,i[0],i[1],word[1:])
if flag:
return flag
self.used[i[0]][i[1]] = False # 状态回退
return False
s = Solution()
print(s.exist([["C","A","A"],["A","A","A"],["B","C","D"]]
,"AAB"))