思路:數組
#遍歷二維數組 for i in range(len(board)): for j in range(len(board[0])): #調用helper函數 if self.helper(board,i,j,word,0): return True return False
#定義helper函數: def helper(self,board,i,j,word,index): #若是當前的下標與單詞的長度相等,說明前面的全部字母都找到了匹配,返回True if index == len(word): return True #若是當前的下標越界,或是當前的元素字母與單詞中的字母不一樣,返回False if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[index]: return False #要把當前已經通過的數組元素標記 board[i][j] = "*" #遞歸調用當前元素的上下左右,看有沒有與單詞的下一個字母相同的 found = self.helper(board,i+1,j,word,index+1)\ or self.helper(board,i,j+1,word,index+1)\ or self.helper(board,i-1,j,word,index+1)\ or self.helper(board,i,j-1,word,index+1) #已經標記的值要復原 board[i][j] = word[index] return found
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ for i in range(len(board)): for j in range(len(board[0])): if self.helper(board,i,j,word,0): return True return False def helper(self,board,i,j,word,index): if index == len(word): return True if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[index]: return False board[i][j] = "*" found = self.helper(board,i+1,j,word,index+1)\ or self.helper(board,i,j+1,word,index+1)\ or self.helper(board,i-1,j,word,index+1)\ or self.helper(board,i,j-1,word,index+1) board[i][j] = word[index] return found