题目要求:
思路:
思路1:伪代码
主函数(矩阵,路径)
如果矩阵为空(两种空情况):
直接返回False
否则:
遍历矩阵所有点(根据题意,每个点都有可能是起点)
如果是起点,且调用查找函数(矩阵,已走路径列表,待查路径)返回True
#已走路径列表对应的点+待查路径 = 主函数传入路径()
直接退出循环,返回True
如果遍历结束,为得到True结果,矩阵不存在该路径,返回False
查找函数(矩阵,已走路径列表,待查路径)
如果待查找路径为空:
说明路径已被全部找到,此时已走路径列表即为路线每个对应点位置,返回True即可
否则:
说明还存在为查找的值,此时应取待查路径的第一个值进行查找即word[0]
此时,先定位起点,即上个点所在位置,应为已走路径列表最后一个元素,获取到其下标m,n
如果 0 < m:说明起点上方点可走
如果该点是值等于被查点值且不在已走路径列表中,说明上方点位置可以走
将该点加入已走列表中
判断递归并判断是否能走通(等到True)
如果能走通,说明已经找到该路径,返回True即可
如果不能走通,说明该点不符合要求,从已走路径中去掉该点,然后继续判断下,左,右,点位置是否能走通即可
如果 m < len(matrix)-1:说明起点下方点可走
操作同上
如果 0 < n:说明起点左方点可走
操作同上
如果 n < len(matrix[0]) - 1:说明起点右方点可走
操作同上
否则说明上下左右都走不通,即查不到路线,直接返回False即可
代码如下:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix char字符型二维数组
# @param word string字符串
# @return bool布尔型
#
class Solution:
def hasPath(self , matrix, word):
if len(matrix)==0 or len(matrix[0])==0:
return False
else:
for m in range(len(matrix)):
for n in range(len(matrix[0])):
if matrix[m][n] == word[0] and self.find(matrix,[(m,n)],word[1:]):
return True
return False
# write code here
def find(self,matrix,pathList,word):
if word == '':
return True
else:
m,n = pathList[-1]
if 0 < m:
if matrix[m-1][n] == word[0] and (m-1,n) not in pathList:
pathList.append((m-1,n))
if self.find(matrix,pathList,word[1:]):
return True
pathList.remove((m - 1, n))
if m < len(matrix)-1:
if matrix[m+1][n] == word[0] and (m+1,n) not in pathList:
pathList.append((m+1,n))
if self.find(matrix,pathList,word[1:]):
return True
pathList.remove((m + 1, n))
if 0 < n:
if matrix[m][n-1] == word[0] and (m,n-1) not in pathList:
pathList.append((m,n-1))
if self.find(matrix,pathList,word[1:]):
return True
if n < len(matrix[0]) - 1:
if matrix[m][n+1] == word[0] and (m,n+1) not in pathList:
pathList.append((m,n+1))
if self.find(matrix,pathList,word[1:]):
return True
pathList.remove((m, n + 1))
return False