1class Solution:2def exist(self, board: List[List[str]], word: str) -> bool:3m = len(board)4n = len(board[0])56marked = set() # visited by the dfs78def dfs(cell: Tuple[int, int], wp: int) -> bool:9i = cell[0]10j = cell[1]1112if wp == len(word):13return True1415# Get appropriate neighbours and perform dfs on them16# When going on dfs, we mark certain cells, we should remove #17# them from the marked list after we return from the dfs18marked.add((i, j))19neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]20for x, y in neibs:21if (22x < 023or y < 024or x >= m25or y >= n26or (x, y) in marked27or board[x][y] != word[wp]28):29continue3031if dfs((x, y), wp + 1):32return True3334marked.remove((i, j))35return False3637for i in range(m):38for j in range(n):39if board[i][j] == word[0]:40if dfs((i, j), 1):41return True4243return False