题目
思路
代码
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows = len(board)
cols = len(board[0])
def dfs(x,y,k):
if not 0<=x<rows or not 0<=y<cols:
return False
if board[x][y]!=word[k]:
return False
if k==len(word)-1:
return True
k+=1
board[x][y]=' '
res= dfs(x+1,y,k) or dfs(x-1,y,k) or dfs(x,y+1,k) or dfs(x,y-1,k)
board[x][y]=word[k-1]
return res
for curX in range(0,rows):
for curY in range(0,cols):
if dfs(curX,curY,0):
return True
return False