1 # -*- coding:utf-8 -*- 2 class Solution: 3 def __init__(self): 4 self.visited = [] 5 6 def dfs(self,matrix,rows,cols,path,i,j,direction,k): 7 if k >= len(path): 8 return True 9 if i < 0 or i >= rows or j < 0 or j >=cols: 10 return False 11 if self.visited[i][j] == 1: 12 return False 13 if matrix[i][j] == path[k]: 14 self.visited[i][j] = 1 15 tg = False 16 for direct in direction: 17 x = i + direct[0] 18 y = j + direct[1] 19 tg = tg or self.dfs(matrix,rows,cols,path,x,y,direction,k+1) 20 self.visited[i][j] = 0 21 return tg 22 else: 23 return False 24 25 def hasPath(self, matrix, rows, cols, path): 26 array = [[‘ ‘ for c in range(cols)]for r in range(rows)] 27 idx = 0 28 for i in range(rows): 29 for j in range(cols): 30 cur = matrix[idx] 31 idx += 1 32 array[i][j] = cur 33 34 direction = [[0,1],[0,-1],[1,0],[-1,0]] 35 self.visited = [[0 for c in range(cols)]for r in range(rows)] 36 for i in range(rows): 37 for j in range(cols): 38 if self.dfs(array,rows,cols,path,i,j,direction,0): 39 return True 40 return False 41 # write code here
原文:https://www.cnblogs.com/asenyang/p/11015184.html