剑指Offer(二)——回溯(矩阵中的路径)[0]

题目

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如如下矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param matrix string字符串 
# @param rows int整型 
# @param cols int整型 
# @param str string字符串 
# @return bool布尔型
#
class Solution:
    def hasPath(self , matrix , rows , cols , str ):
        # write code here
        if not matrix and rows<=0 and cols<=0 and str==None:
            return False
        boolmatrix=[0]*(rows*cols)
        pathLength=0
        for row in range(rows):
            for col in range(cols):
                if self.hasPathCore(matrix, rows, cols, row,col,str,pathLength,boolmatrix):
                    return True
        return False
    def hasPathCore(self,matrix,rows,cols,row,col,str,pathLength,boolmatrix):
        if len(str)==pathLength:
            return True
        hasNextPath=False
        if (row>=0 and row<rows and col>=0 and col<cols and matrix[row*cols+col]==str[pathLength] and not boolmatrix[row*cols+col]):
            pathLength+=1
            boolmatrix[row*cols+col]=True
            hasNextPath=(self.hasPathCore(matrix, rows, cols, row-1, col, str, pathLength, boolmatrix) or self.hasPathCore(matrix, rows, cols, row+1, col, str, pathLength, boolmatrix) or self.hasPathCore(matrix, rows, cols, row, col-1, str, pathLength, boolmatrix) or self.hasPathCore(matrix, rows, cols, row, col+1, str, pathLength, boolmatrix))
            if not hasNextPath:
                pathLength-=1
                boolmatrix[row*cols+col]=False
        return hasNextPath
            
            
            
            
            

猜你喜欢

转载自blog.csdn.net/caicai0001000/article/details/114272076
今日推荐