zoukankan      html  css  js  c++  java
  • 剑指Offer 12 矩阵中的路径

    矩阵中的路径

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

     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             for direct in direction:
    16                 x = i + direct[0]
    17                 y = j + direct[1]
    18                 if self.dfs(matrix,rows,cols,path,x,y,direction,k+1):
    19                     return True
    20             self.visited[i][j] = 0
    21         else:
    22             return False
    23     
    24     def hasPath(self, matrix, rows, cols, path):
    25         array = [[' ' for c in range(cols)]for r in range(rows)]
    26         idx = 0
    27         for i in range(rows):
    28             for j in range(cols):
    29                 cur = matrix[idx]
    30                 idx += 1
    31                 array[i][j] = cur
    32 
    33         direction = [[0,1],[0,-1],[1,0],[-1,0]]
    34         self.visited = [[0 for c in range(cols)]for r in range(rows)]
    35         for i in range(rows):
    36             for j in range(cols):
    37                 if self.dfs(array,rows,cols,path,i,j,direction,0):
    38                     return True
    39         return False
    40         # write code here
  • 相关阅读:
    Java中Io类-File类的构造方法
    hadoop的wordcount例子运行
    关于“javax.servlet.include.request_uri”属性值
    如何高效地分析框架源码
    代码重构的技巧——合理使用@Deprecated
    spring的事件机制
    在eclipse中使用jetty插件替代m2e开发调试maven web项目
    maven多配目配置总结
    如何禁止anonymous用户访问nexus
    efront二次开发记要
  • 原文地址:https://www.cnblogs.com/asenyang/p/11015184.html
Copyright © 2011-2022 走看看