What is wrong with the path in the offer matrix?

 

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.res = False
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        if not path:return not matrix
        if not matrix:return False
        
        def dfs(matrix, visit, idx, idy, cur):
            print(cur)
            if cur == len(path):
                self.res = True
                return
            if not visit[idx][idy] and matrix[idx][idy] == path[cur]:
                visit[idx][idy] = 1
                for i in [1,-1,0,0]:
                    for j in [0,0,1,-1]:
                        idx_,idy_ = idx+i,idy+j
                        if idx_ >= 0 and idx_ < len(matrix) and idy_ >=0 and idy_ < len(matrix[0]):
                            dfs(matrix, visit, idx_, idy_, cur+1)
                visit[idx][idy] = 0
        
        visit = [[0] * len(matrix[0]) for _ in range(len(matrix))]
        for idx in range(len(matrix)):
            for idy in range(len(matrix[0])):
                dfs(matrix,visit,idx,idy,0)
        return self.res
matrix = [['A', 'B', 'C', 'E'],
       ['S', 'F', 'C', 'S'],
       ['A', 'D', 'E', 'E']]
rows = 3
cols = 4
path = "ABCCED"
Solution().hasPath(matrix, rows, cols, path)

 

Guess you like

Origin blog.csdn.net/u011939633/article/details/106631238