题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e | s f c s | a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:这是一个可以使用回溯法的经典题型
【回溯法即从解决问题的每一步的所有可能项里系统的选择出一个可行的解决方案。回溯法可以形象的用树状结构来表示,问题的每个步骤的选项可以堪称是节点,最后要到达的状态是某个叶节点,如果在叶节点的状态不满足约束条件,那么只能回溯到上一个 节点,如果所有节点的所有选项都已经被尝试还没有满足约束条件,那么说明该问题无解。】
算法步骤:
首先定义两个变量,分别是记录矩阵的元素位置是否已经在路径之中的markmatrix和记录目前已经匹配的字符长度;
接着从坐上角元素开始遍历,找到第一个匹配的元素之后开始回溯,分别查找其上下左右的元素是否和n+1字符元素匹配,如有匹配则继续进行下一个节点搜索,否则返回上一匹配元素的位置继续其他路径搜寻。
代码实现:
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix or rows < 0 or cols < 0 or path is None:
return False
markmatrix=[0]*(rows*cols)
pathindex = 0
for row in range(rows):
for col in range(cols):
if self.has_path_core(matrix,row,col,rows,cols,path,pathindex,markmatrix):
return True
return False
def has_path_core(self,matrix,row,col,rows,cols,path,pathindex,markmatrix):
if pathindex == len(path):
return True
has_path = False
if row>=0 and row<rows and col>=0 and col <cols and matrix[row*cols+col]== path[pathindex] and not markmatrix[row*cols+col]:
pathindex +=1
markmatrix[row*cols+col] = True
has_path = self.has_path_core(matrix,row+1,col,rows,cols,path,pathindex,markmatrix) \
or self.has_path_core(matrix,row-1,col,rows,cols,path,pathindex,markmatrix) \
or self.has_path_core(matrix,row,col+1,rows,cols,path,pathindex,markmatrix) \
or self.has_path_core(matrix,row,col-1,rows,cols,path,pathindex,markmatrix)
if not has_path:
pathindex-=1
markmatrix[row*cols+col] = False
return has_path
运行结果.png