矩阵中的路径python

在这里插入图片描述
思路:和机器人的运动范围类似
运用回溯法和DFS方法进行遍历比较

  • 遍历整个矩阵,找到和字符串匹配的第一个字符

  • 然后遍历该字符的上下左右字符,如有匹配,就把该匹配字符作为节点,继续匹配其上下左右字符,如不匹配,则退回到上个字符,继续匹配

  • 为了防止重复,需要一个矩阵来存储走过的字符位置

注意: 本题给定的是一个字符串,在对字符串(一维)进行索引遍历的时候,应i,j表示矩阵索引,则字符串索引应该为 i * cols + j

代码:

# -*- coding:utf-8 -*-
class Solution:
    def find_path(self, matrix, rows, cols, path, path_number, i, j, boolean_if_go):
        has_next_path = False
        if len(path) == path_number:
            return True
        if i < rows and j < cols and i >= 0 and j >= 0 and matrix[i * cols + j] == path[path_number] and\
                not boolean_if_go[i * cols + j]:
            path_number += 1
            boolean_if_go[i * cols + j] = True
            has_next_path = (self.find_path(matrix, rows, cols, path, path_number, i-1, j, boolean_if_go)
                             or self.find_path(matrix, rows, cols, path, path_number, i, j+1, boolean_if_go)
                             or self.find_path(matrix, rows, cols, path, path_number, i+1, j, boolean_if_go)
                             or self.find_path(matrix, rows, cols, path, path_number, i, j-1, boolean_if_go))
            if not has_next_path:
                boolean_if_go[i * cols +j] = False
                path_number -= 1
        return has_next_path

    def hasPath(self, matrix, rows, cols, path):
        # write code here
        boolean_if_go = [0] * (rows * cols)
        path_number = 0
        for i in range(rows):
            for j in range(cols):
                if self.find_path(matrix, rows, cols, path, path_number, i, j, boolean_if_go):
                    return True
        return False


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值