暴力回溯法可以解决,但是会超时

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        visited = []
        direction = [-1,0,1,0,-1]
        m = len(board)
        n = len(board[0])
        
        def backTracking(start,idx):
            if idx>=len(word):
                return True
            for i in range(4):
                x = start[0] + direction[i]
                y = start[1] + direction[i+1]
                if 0<=x<m and 0<=y<n and (x,y) not in visited and board[x][y] == word[idx]:
                    visited.append((x,y))
                    if backTracking((x,y),idx+1):
                        return True
                    visited.pop()
            return False
            
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    visited.append((i,j))
                    if backTracking((i,j),1):
                        return True
                    visited.pop()
                else:
                    continue
        return False

然后通过把visited换成对board操作,成功通过

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        
        direction = [-1,0,1,0,-1]
        m = len(board)
        n = len(board[0])
        
        def backTracking(start,idx):
            if idx>=len(word):
                return True
            for i in range(4):
                x = start[0] + direction[i]
                y = start[1] + direction[i+1]
                if 0<=x<m and 0<=y<n and (x,y) and board[x][y] == word[idx]:
                    tmp = board[x][y]
                    board[x][y] = "*"
                    if backTracking((x,y),idx+1):
                        return True
                    board[x][y] = tmp
            return False
            
        for i in range(m):
            for j in range(n):
                if board[i][j] == word[0]:
                    tmp = board[i][j]
                    board[i][j] = "*"
                    if backTracking((i,j),1):
                        return True
                    board[i][j] = tmp
                else:
                    continue
        return False

79. Word Search刷题笔记_List