请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:
1.遍历所有初始点,对每个点进行dfs
2.编写dfs函数时,注意:当第n步不满足时,回退到上一步
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
#深度优先搜索
#标记匹配到字符串第几个字符
count=0
n=len(path)
for i in range(rows):
for j in range(cols):
#创建一个矩阵标记是否放过 注意每次要还原这个矩阵
bool_mat=[[False]*cols for k in range(rows)]
res=self.dfs(matrix, rows, cols, path,bool_mat,i,j,count,n)
if res:return True
return False
def dfs(self,matrix, rows, cols, path,bool_mat,i,j,count,n):
if count==n:return True
has_path=False
if bool_mat[i][j]==False:
if matrix[i*cols+j]==path[count]:
bool_mat[i][j]=True
count+=1
if count==n:return True
if i>0 and self.dfs(matrix,rows, cols, path,bool_mat,i-1,j,count,n):
has_path=True
if i<rows-1 and self.dfs(matrix,rows, cols, path,bool_mat,i+1,j,count,n):
has_path=True
if j>0 and self.dfs(matrix,rows, cols, path,bool_mat,i,j-1,count,n):
has_path=True
if j<cols-1 and self.dfs(matrix,rows, cols, path,bool_mat,i,j+1,count,n):
has_path=True
if not has_path:
count-=1
bool_mat[i][j]==False
return has_path