思路:和机器人的运动范围类似
运用回溯法和DFS方法进行遍历比较
-
遍历整个矩阵,找到和字符串匹配的第一个字符
-
然后遍历该字符的上下左右字符,如有匹配,就把该匹配字符作为节点,继续匹配其上下左右字符,如不匹配,则退回到上个字符,继续匹配
-
为了防止重复,需要一个矩阵来存储走过的字符位置
注意: 本题给定的是一个字符串,在对字符串(一维)进行索引遍历的时候,应i,j表示矩阵索引,则字符串索引应该为 i * cols + j
代码:
# -*- coding:utf-8 -*-
class Solution:
def find_path(self, matrix, rows, cols, path, path_number, i, j, boolean_if_go):
has_next_path = False
if len(path) == path_number:
return True
if i < rows and j < cols and i >= 0 and j >= 0 and matrix[i * cols + j] == path[path_number] and\
not boolean_if_go[i * cols + j]:
path_number += 1
boolean_if_go[i * cols + j] = True
has_next_path = (self.find_path(matrix, rows, cols, path, path_number, i-1, j, boolean_if_go)
or self.find_path(matrix, rows, cols, path, path_number, i, j+1, boolean_if_go)
or self.find_path(matrix, rows, cols, path, path_number, i+1, j, boolean_if_go)
or self.find_path(matrix, rows, cols, path, path_number, i, j-1, boolean_if_go))
if not has_next_path:
boolean_if_go[i * cols +j] = False
path_number -= 1
return has_next_path
def hasPath(self, matrix, rows, cols, path):
# write code here
boolean_if_go = [0] * (rows * cols)
path_number = 0
for i in range(rows):
for j in range(cols):
if self.find_path(matrix, rows, cols, path, path_number, i, j, boolean_if_go):
return True
return False