我正在尝试使用 python 解决leetcode 79. 单词搜索,但是在调试我的解决方案时遇到了一些麻烦。坚持测试用例:{[["A","B","C","E"],["S","F","E","S"],["A","D ","E","E"]] "ABCESEEEFS"},它不会通过上面的测试用例,需要一些帮助,谢谢。
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(board, word, used, x, y):
if not word: return True
direction = [[0, 1],[0, -1],[1, 0],[-1, 0]]
if (0 <= x < len(board)) and (0 <= y < len(board[0])) and ((x, y) not in used) and (board[x][y] == word[0]):
used.add((x, y))
return (dfs(board, word[1:], used, x + direction[0][0], y + direction[0][1]) or
dfs(board, word[1:], used, x + direction[1][0], y + direction[1][1]) or
dfs(board, word[1:], used, x + direction[2][0], y + direction[2][1]) or
dfs(board, word[1:], used, x + direction[3][0], y + direction[3][1]))
return False
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(board, word, set(), i, j) == True: return True
return False