首先,这一题的目的是要求在矩阵中找到符合要求的路径,而在寻找路径的过程中,找到一个点要考虑他的下一点是否符合要求,倘若不符合要求则要返回上一节点,再根据上一节点继续寻找别的节点,依次而行; 其中,我感觉最重要的时要考虑下一节点是否被重复选中,所以要选择一个空白的矩阵来记录当时的节点选中情况,以便在每次查看节点时能够准确的检查节点是否被选中过;另外这种不断的选择正确节点的路径的方式说白了就是一个递归的方法,所以考虑好递归的设置方式很重要,以下是相关代码:
class Solution: def hasPath(self,martic,rows,cols,path): if not martic or rows<0 or cols<0: return False markmartic=[0]*(rows*cols) pathIndex=0 for row in range(rows): for col in range(cols): if self.hasPathCore(martic,rows,cols,row,col,path,markmartic,pathIndex): return True return False #markmartic是一个空白矩阵,实时监控节点是否被选中过 def hasPathCore(self,martic,rows,cols,row,col,path,markmartic,pathIndex): if pathIndex==len(path): return True hasPath=False if row>=0 and row<rows and col>=0 and col<cols and martic[row*cols+col]==path[pathIndex] and not markmartic[rows*cols+col]: pathIndex+=1 markmartic[row*cols+col]=True hasPath=self.hasPathCore(martic,rows,cols,row+1,col,path,markmartic,pathIndex) or \ self.hasPathCore(martic,rows,cols,row,col+1,path,markmartic,pathIndex) or \ self.hasPathCore(martic, rows, cols, row-1, col, path, markmartic, pathIndex) or \ self.hasPathCore(martic, rows, cols, row, col - 1, path, markmartic, pathIndex) if not hasPath: pathIndex-=1 markmartic[row*cols+col]=False return hasPath代码参考网站:https://www.cnblogs.com/yanmk/p/9193625.html
