79. 单词搜索 - 力扣(LeetCode)
class Solution:def exist(self, board: List[List[str]], word: str) -> bool:if not board or not board[0]:return Falserows, cols = len(board), len(board[0])def backtrack(r, c, index):if index == len(word):return Trueif r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:return Falsetemp, board[r][c] = board[r][c], '#' # 标记访问过的单元格found = (backtrack(r + 1, c, index + 1) orbacktrack(r - 1, c, index + 1) orbacktrack(r, c + 1, index + 1) orbacktrack(r, c - 1, index + 1))board[r][c] = temp # 回溯,恢复原状return foundfor i in range(rows):for j in range(cols):if backtrack(i, j, 0):return Truereturn False