65.矩阵中的路径
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
解题思路
这题用的是回溯法思想。首先在矩阵中找到字符串的第一个字母,如果有,则根据字母在字符串的位置递归查找第二个字母。
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):
for j in range(cols):
if self.search(x, i, j, path):
return True
def search(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.search(matrix, i - 1, j, p[1:]):
return True
if i < len(matrix) - 1 and self.search(matrix, i + 1, j, p[1:]):
return True
if j < len(matrix[0]) - 1 and self.search(matrix, i, j + 1, p[1:]):
return True
if j > 0 and self.search(matrix, i, j - 1, p[1:]):
return True
matrix[i][j] = p[0]
return False
else:
return False