题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
解题思路:回溯法
- 首先把matrix转变为一个二维矩阵。
x = [list(matrix[cols*i:cols*i+cols]) for i in range(rows)]
字符 | 字符的位置 |
---|---|
[[‘A’,‘B’,‘C’,‘E’] | [[(0,0),(0,1),(0,2),(0,3)] |
[‘S’,‘F’,‘C’,‘S’] | [(1,0),(1,1),(1,2),(1,3)] |
[‘A’,‘D’,‘E’,‘E’]] | [(2,0),(2,1),(2,2),(2,3)]] |
- 然后通过二维矩阵确定第一个字符的位置,然后安装上下左右开始搜索第二个字符,依次进行,直到最后一个字符
python 代码
# -*- coding:utf-8 -*-
#回溯法
#遍历矩阵中的每一个位置
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix:
return False
if not path:
return True
x = [list(matrix[cols*i:cols*i+cols]) for i in range(rows)]
for i in range(rows): # [0,1,2]
for j in range(cols): # [0,1,2,3]
if self.exist_helper(x, i, j, path):
return True
return False
def exist_helper(self, matrix, i, j, p):
if matrix[i][j] == p[0]:
if not p[1:]:
return True
matrix[i][j] = ''
# 往上
if i > 0 and self.exist_helper(matrix, i-1, j, p[1:]):
return True
# 往下
if i < len(matrix)-1 and self.exist_helper(matrix, i+1, j ,p[1:]):
return True
# 往左
if j > 0 and self.exist_helper(matrix, i, j-1, p[1:]):
return True
# 往右
if j < len(matrix[0])-1 and self.exist_helper(matrix, i, j+1, p[1:]):
return True
# 重置
matrix[i][j] = p[0]
return False
else:
return False
s = Solution()
res = s.hasPath("ABCESFCSADEE",3,4,"ABCCED")
print(res)