剑指offer-矩阵中的路径(python详细解读)

题目描述

在这里插入图片描述

解题方法

首先说下解决这个题目时需要注意的问题:
1.给定的matrix,并不是矩阵形式,而是字符串形式。一开始我就在这里踩坑了,但其实看官方给定的函数(如下)就可以看出,matrix不是直接矩阵形式,如果是的话,就不用给rows和cols了,对吧。所以,如果要得到第i行,第j列的元素,应该是matrix [ i*cols + j ] (其中i表示rows的索引,j表示cols索引)

在这里插入图片描述
2. 对于字符串‘bcccc’在例子矩阵matrix中其实并不存在。如果不做任何处理,程序会重复遍历相同元素’c’,而使得‘bcccc’存在于matrix中的假象。所以应该怎么样避免重复遍历呢,给出的方法是使matrix[icols+j]符合条件且遍历过的元素为’0’,即matrix[icols+j] = ‘0’。
3. 在回溯的时候,如果一个方向找到满足条件的路径,就直接返回True。找不到,则回溯到另一个方向。
具体代码如下

class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        for i in range(rows):
            for j in range(cols):
                if matrx[i*cols+j] == path[0]:
                   if self.findPath(list(matrix), rows, cols, path[1:], i, j):
                      return True
        return False
    def findPath(self, matrix, rows, cols, path, m, n):
        #结束条件
        if not path:
           return True
        if m>cols or n >rows or m<0 or n<0:
          return False
        #避免重复遍历  
        matrix[m*cols+n] = '0'
        
        if n+1 < rows and matrix[m*cols+n+1]==path[0]:
           return self.findPath(matrix, rows, cols, path[1:], m, n+1)
        if n-1 >= 0 and matrix[m*cols+n-1]==path[0]:
           return self.findPath(matrix, rows, cols, path[1:], m, n-1)
        if m+1 < cols and matrix[(m+1)*cols+n]==path[0]:
           return self.findPath(matrix, rows, cols, path[1:], m+1, n)
        if m-1 > 0 and matrix[(m-1)*cols+n]==path[0]:
           return self.findPath(matrix, rows, cols, path[1:], m-1, n)

注意和上一篇博文《机器人的运动范围》做对比,虽然都用到了回溯,但是提取的信息不同,这个回溯找到一个满足条件的就结束,而《机器人的运动范围》是要累计所有满足条件的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值