题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路
回溯法
- 通过循环来不断地投放第一个节点
- 在满足【矩阵规则,是否进入过该点(需要设置一个标记矩阵),是否等于要找的点】的条件下
- 如果已找到匹配点,标记矩阵标为True
- 继续向上,向下,向左,向右地去查找下一个点
- 没找到下一个节点就返回到上一个要找的节点,同时上一个节点的标记矩阵改为False
- 递归的出口:找到的节点数等于给定的路径长度,满足则True,否则False
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix or not path or rows<=0 or cols<=0:
return False
markmatrix=[0]*(rows*cols)
for row in range(rows):
for col in range(cols):
if self.findpath(matrix,rows,cols,path,row,col,markmatrix,0):
return True
return False
def findpath(self,matrix,rows,cols,path,row,col,markmatrix,index):
if index==len(path):
return True
isfind=False
if row>=0 and col>=0 and row<rows and col<cols and matrix[row*cols+col]==path[index] and not markmatrix[row*cols+col]:
index+=1
markmatrix[row*cols+col]=True
isfind=self.findpath(matrix,rows,cols,path,row+1,col,markmatrix,index) or \
self.findpath(matrix,rows,cols,path,row-1,col,markmatrix,index) or \
self.findpath(matrix,rows,cols,path,row,col+1,markmatrix,index) or \
self.findpath(matrix,rows,cols,path,row,col-1,markmatrix,index)
if not isfind:
index-=1
markmatrix[row*cols+col]=False
return isfind
测试用例
if __name__=='__main__':
s=Solution()
numbers=['a','b','c','e','s','f','c','s','a','d','e','e']
path1=['b','c','c','e','d']
path2=['a','b','c','b']
print(s.hasPath(numbers,3,4,path1))
print(s.hasPath(numbers,3,4,path2))