回溯要注意为每个子树建立建立新的资源,避免回溯后不同子树相互影响
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
M,N = len(board),len(board[0])
word = list(word)
def tra(word,board,m,n,wcur,si):
if wcur==len(word)-1 and word[wcur]==board[m][n]:
return True
if m-1>=0 and si[m-1][n]==0 and board[m-1][n]==word[wcur+1]:
newsi = copy.deepcopy(si)
newm,newn = m-1,n
newwcur = wcur+1
newsi[newm][newn]=1
if tra(word,board,newm,newn,newwcur,newsi):return Tr