剑指offer矩阵中的路径
本地测试用例通过,在线却输出相反的结果?是Python3和Python2的原因吗?
# -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here m = [[0]*cols for i in range(rows)] for i in range(rows): for j in range(cols): m[i][j] = matrix[i*cols+j] for i in range(rows): for j in range(cols): visited = [[0]*cols for i in range(rows)] if self.dfs(m,rows,cols,path,visited,i,j,0): return True return False def dfs(self,matrix,rows,cols,path,visited,i,j,index): if index == len(path): return True if i < 0 or i >= rows or j < 0 or j >= cols or matrix[i][j] != path[index] or visited[i][j] == 1: return False visited[i][j] = 1 index += 1 result = self.dfs(matrix,rows,cols,path,visited,i+1,j,index) or self.dfs(matrix,rows,cols,path,visited,i-1,j,index) or self.dfs(matrix,rows,cols,path,visited,i,j+1,index) or self.dfs(matrix,rows,cols,path,visited,i,j-1,index) visited[i][j] = 0 return result
#笔试题目##Python#