python官方题解--矩阵中的路径

矩阵中的路径

http://www.nowcoder.com/questionTerminal/c61c6999eecb4b8f88a98f66b273a3cc

此题采用回溯发来进行求解,在说之前我想告诉大家,如果大家看过之前别人提交的py版本的代码,会发现不能通过全部的测试用例,现在我根据剑指offer书中的思路写下如下py的代码,希望您批评指正!!!

class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        if not matrix  or  not path :
            return False
        visited = [0] * len(matrix)
        result = ''
        length = 0
        for row in range(rows):
            for col in range(cols): 
                if (self.hasPathCore(matrix, path, rows, cols, row, col, visited, result, length)):
                    return True
        del visited        
        return False

    def hasPathCore(self, matrix, path, rows, cols, row, col, visited, result, length):
        if result == path:
            return True
        hasPath = False
        if (row >= 0 and row < rows and col >= 0 and col < cols and (not visited[row*cols + col])\
            and path[length] == matrix[row*cols + col]):
            length += 1
            visited[row*cols + col] = 1
            result += matrix[row*cols + col]
            hasPath = self.hasPathCore(matrix, path, rows, cols, row-1, col, visited, result, length) or \
                      self.hasPathCore(matrix, path, rows, cols, row+1, col, visited, result, length) or \
                      self.hasPathCore(matrix, path, rows, cols, row, col+1, visited, result, length) or \
                      self.hasPathCore(matrix, path, rows, cols, row, col-1, visited, result, length) 
            if (not hasPath):
                length -= 1
                visited[row*cols + col] = 0
                result = result[:-1]
        return hasPath
全部评论

相关推荐

昨天 15:02
门头沟学院 Java
刚打开网申页面就不想填了,还是不要为难自己了
poppinzhan...:多益老行业毒瘤了,碰到徐波这种恶心的烂人,去了也是受罪。
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务