题目描述
解题方法
首先说下解决这个题目时需要注意的问题:
1.给定的matrix,并不是矩阵形式,而是字符串形式。一开始我就在这里踩坑了,但其实看官方给定的函数(如下)就可以看出,matrix不是直接矩阵形式,如果是的话,就不用给rows和cols了,对吧。所以,如果要得到第i行,第j列的元素,应该是matrix [ i*cols + j ] (其中i表示rows的索引,j表示cols索引)
2. 对于字符串‘bcccc’在例子矩阵matrix中其实并不存在。如果不做任何处理,程序会重复遍历相同元素’c’,而使得‘bcccc’存在于matrix中的假象。所以应该怎么样避免重复遍历呢,给出的方法是使matrix[icols+j]符合条件且遍历过的元素为’0’,即matrix[icols+j] = ‘0’。
3. 在回溯的时候,如果一个方向找到满足条件的路径,就直接返回True。找不到,则回溯到另一个方向。
具体代码如下
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrx[i*cols+j] == path[0]:
if self.findPath(list(matrix), rows, cols, path[1:], i, j):
return True
return False
def findPath(self, matrix, rows, cols, path, m, n):
#结束条件
if not path:
return True
if m>cols or n >rows or m<0 or n<0:
return False
#避免重复遍历
matrix[m*cols+n] = '0'
if n+1 < rows and matrix[m*cols+n+1]==path[0]:
return self.findPath(matrix, rows, cols, path[1:], m, n+1)
if n-1 >= 0 and matrix[m*cols+n-1]==path[0]:
return self.findPath(matrix, rows, cols, path[1:], m, n-1)
if m+1 < cols and matrix[(m+1)*cols+n]==path[0]:
return self.findPath(matrix, rows, cols, path[1:], m+1, n)
if m-1 > 0 and matrix[(m-1)*cols+n]==path[0]:
return self.findPath(matrix, rows, cols, path[1:], m-1, n)
注意和上一篇博文《机器人的运动范围》做对比,虽然都用到了回溯,但是提取的信息不同,这个回溯找到一个满足条件的就结束,而《机器人的运动范围》是要累计所有满足条件的。