79. 单词搜索
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
row,col = len(board),;en(board[0])#求其行列
def dfs(x,y,idx):
if idx==len(board)-1:
return True
board[x][y]=='#' #设置走过的为#
choices = [[0,1],[0,-1],[1,0],[-1,0]] #上下左右
for choice in choices:
nx,ny=x+choice[0],y+choice[1]
if 0<=nx<row and o<=ny<col and board[nx][ny]==word[dx+1] and dfs(nx,ny,idx+1):# 判断下一个是否符合
return True
board[x][y]=word[idx]
for i in range(row):
for j in range(col):
if board[i][j]==word[0] and dfs(i,j,0): #起始点相同且回溯下一个符合
return True
return False