classSolution:def__init__(self):
self.history =set()defexist(self, board: List[List[str]], word:str)->bool:if board ==[]or board[0]==[]:returnFalse
m =len(board)
n =len(board[0])for i inrange(m):for j inrange(n):#if board[i][j] == word[0] and len(word):
history =set()if self.search(board,i,j,0,m,n,word,history):returnTruereturnFalsedefsearch(self,board,i,j,index,m,n,word,history):#direction = 0#1:上一次是从左到右 这次不i-1if i <0or j <0or i >= m or j >= n or(i,j)in history:returnFalseif board[i][j]!= word[index]:returnFalse
history.add((i,j))
index +=1if index ==len(word):returnTrue#index表征目前识别正确的索引
h1 = history.copy()
h2 = history.copy()
h3 = history.copy()
h4 = history.copy()returnTrueif(i-1,j)notin history and(self.search(board,i-1,j,index,m,n,word,h1))or(i+1,j)notin history and(self.search(board,i+1,j,index,m,n,word,h2))or(i,j-1)notin history and self.search(board,i,j-1,index,m,n,word,h3)or(i,j+1)notin history and(self.search(board,i,j+1,index,m,n,word,h4))elseFalse