LeetCode79题,不知道哪里有错误
题目是:
79. 单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
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:def dfs(point,rWord):
if rWord=='':
return True
else:
temp = rWord[0]
if point[0]-1 >= 0 and board[point[1]][point[0]-1] == temp:
rWord = rWord[1:]
point=[point[0]-1,point[1]]
dfs(point,rWord)
elif point[0]+1 <len(board[0]) and board[point[1]][point[0]+1] == temp:
rWord = rWord[1:]
point = [point[0]+1,point[1]]
dfs(point,rWord)
elif point[1]-1>=0 and board[point[1]-1][point[0]] == temp:
rWord = rWord[1:]
point = [point[0],point[1]-1]
dfs(point,rWord)
elif point[1]+1<len(board) and board[point[1]+1][point[0]] == temp:
rWord = rWord[1:]
point = [point[0],point[1]+1]
dfs(point,rWord)
else:
return
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
dfs([j,i],word[1:])
return False
我自己在pycharm上调试过了,发现可以进入最后的rWord==''的条件里面,并且读到了return True语句,但是不知道原因最后整个程序还在运行最终return False,求大神看看原因
回答
你调用了dfs(point,rWord),但是没有把结果返回到上一层调用
以上是 LeetCode79题,不知道哪里有错误 的全部内容, 来源链接: utcz.com/a/43193.html