LC79. 单词搜索

回溯,注意返回什么,顺序不能反

def exist(self,board, word):
        row = len(board)
        col = len(board[0])
        mark = [[0 for _ in range(col)] for _ in range(row)]
        def backtrack(r, c, begin):
            if board[r][c] != word[begin]:
                return False
            if len(word)-1 == begin:
                return True
            mark[r][c] = 1
            for nr, nc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
                if 0 <= nr < row and 0 <= nc < col and mark[nr][nc] == 0 and backtrack(nr,nc,begin+1):
                    return True
            mark[r][c] = 0
            return False
        for i in range(row):
            for j in range(col):
                if word[0] == board[i][j]:
                    if backtrack(i, j ,0):
                        return True
        return False

你可能感兴趣的:(LC回溯,深度优先,python)