题目描述:
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路:
创建一个标记矩阵,存经过的点,遍历数组,如果相同就找上下左右和path的后一个元素是否相同,主要实现helper函数
代码:
class Solution:
def hasPath(self, matrix, rows, cols, path):
t = [list(matrix[t*cols:t*cols+cols]) for t in range(rows)]
res = False
for i in range(rows):
for j in range(cols):
if t[i][j] == path[0]:
mask = [[1]*cols for _ in range(rows)]
res = self.helper(t, path, mask, i, j, 0)
if res:
return True
return res
def helper(self, a, s, mask, i, j, id):
import copy
if a[i][j] == s[id] and mask[i][j]:
if id == len(s)-1:
return True
mask[i][j] = 0
h = copy.deepcopy(mask)
left = j - 1 >= 0 and self.helper(a, s, h, i, j-1, id+1)
if left:
return True
h = copy.deepcopy(mask)
up = i - 1 >= 0 and self.helper(a, s, h, i-1, j, id+1)
if up:
return True
h = copy.deepcopy(mask)
down = i + 1 < len(a) and self.helper(a, s, h, i+1, j, id+1)
if down:
return True
h = copy.deepcopy(mask)
right = j + 1 < len(a[0]) and self.helper(a, s, h, i, j+1, id+1)
if right:
return True
return False
else:
return False