剑指offer 矩阵中的路径 回溯

# coding:utf-8

# !/usr/bin/env python

# Time: 2018/6/11 9:09

# Author: sty

# File: Findpath.py

next_state = [[0, -1], [0, 1], [1, 0], [-1, 0]]

class MatrixPath():
    def has_path(self, array, rows, cols, str):
        if rows == 0 or cols == 0:
            return False
        matrix = []
        marked = [[False] * cols for _ in range(rows)]
        row_info = []
        index = 0
        for row in range(rows):
            for col in range(cols):
                row_info.append(array[index])
                index += 1
            matrix.append(row_info)
            row_info = []
        for row in range(rows):
            for col in range(cols):
                if self.judge(matrix, str, marked, 0, row, col, rows, cols):
                    return True
        return False

    def judge(self, matrix, str, marked, path_len, row, col, rows, cols):
        if path_len == len(str):
            return True
        if row < 0 or row >= rows or col < 0 or col >= cols or matrix[row][col] != str[path_len] \
                or marked[row][col] is True:
            return False
        marked[row][col] = True
        for n in next_state:
            # 这里的path_len+1很容易忘记,同时row和col也要相应的变化
            if self.judge(matrix, str, marked, path_len + 1, row+n[0], col+n[1], rows, cols):
                return True
        marked[row][col] = False
        return False



a = MatrixPath()
print(a.has_path('abcesfcsadee', 3, 4, 'bcced'))
print(a.has_path('abcesfcsadee', 3, 4, 'abcb'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值