当前位置: 首页 > 后端技术 > Python

力扣79.词搜索Python实现

时间:2023-03-26 12:26:11 Python

题目要求:思路:先遍历数组,找到一个可能的起点,定义一个辅助函数,用于遍历当前起点的上下左右元素,看是否有下一个数字匹配给定的单词。如果辅助函数被递归调用为next左右下标越界或者当前数组元素与当前单词的字母不同时,返回False核心代码:#遍历二维数组foriinrange(len(board)):forjinrange(len(board[0])):#Callthehelperfunctionifself.helper(board,i,j,word,0):returnTruereturnFalse#定义helperfunction:defhelper(self,board,i,j,word,index):#如果当前下标等于单词的长度,说明前面的所有字母都找到了匹配,返回Trueifindex==len(word):returnTrue#如果当前下标越界,或者当前元素字母在word不同字母中,则返回Falseifi<0ori>=len(board)orj<0orj>=len(board[0])orboard[i][j]!=word[index]:returnFalse#标记当前传递的数组元素board[i][j]="*"#递归调用top,bottom,left,andright当前元素看是否t这是与单词的下一个字母相同的任何发现found=self.helper(board,i+1,j,word,index+1)\或self.helper(board,i,j+1,word,index+1)\或self.helper(board,i-1,j,word,index+1)\或self.helper(board,i,j-1,word,index+1)#已标记的值要复原board[i][j]=word[index]returnfound完整代码:classSolution(object):defexist(self,board,word):""":类型板:列表[列表[str]]:类型词:str:rtype:bool“”“对于范围内的我(len(板)):对于范围内的j(len(板[0])):如果自我。helper(board,i,j,word,0):返回True返回Falsedefhelper(self,board,i,j,word,index):如果index==len(word):如果i<0或i,则返回True>=len(board)orj<0orj>=len(board[0])orboard[i][j]!=word[index]:returnFalseboard[i][j]="*"找到=self.helper(board,i+1,j,word,index+1)\或self.helper(board,i,j+1,word,index+1)\或self.helper(board,i-1,j,word,index+1)\或self.helper(board,i,j-1,word,index+1)board[i][j]=word[index]返回成立