mycode 错误,因为借鉴了Number of Islands问题中的方法,导致在for循环中即使已经出现了答案,也还会继续遍历。但是两个题目的不同时,island需要找出所有的情况,这个题只需要找到第一个完整结果就可以返回
参考:
def exist(board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ def find(board, word, i, j, m, n): if word == '': print('if',i,j) return True if i < 0 or i >= m or j < 0 or j >= n: print('if2',i,j) return False elif word[0] == board[i][j]: print('elif',i,j) board[i][j] = None #标记 res = find(board, word[1:], i+1, j, m, n)or find(board, word[1:], i-1, j, m, n)or find(board, word[1:], i, j+1, m, n)or find(board, word[1:], i, j-1, m, n) board[i][j] = word[0] #恢复原来的值 return res print(i,j) if len(word) == 0: return True m = len(board) if m == 0: return False n = len(board[0]) for i in range(m): for j in range(n): if find(board, word, i, j, m, n): return True return False