題目描述
請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑
。路徑可以從矩陣中的任意一個格子開始
,每一步可以在矩陣中向左
,向右
,向上
,向下
移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能
再進入該格子。
示例
例如
:
a b c e
s f c s
a d e e
矩陣中包含
一條字符串"bcced
“的路徑,但是矩陣中不包含”abcb
"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能
再次進入該格子。
分析
- 首先確定利用回溯法進行求解。
- 確立解空間-
子集樹空間
。
- 利用深度優先搜索。
- 確立剪枝條件。
- 搜索越出矩陣範圍,停止向下搜索,剪枝。
- 不是目標字符,停止向下搜索,剪枝。
- 已經被搜索比較過,停止向下所搜,剪枝。
- 確立解空間-
代碼
class Solution:
def __init__(self):
self.matrix = []
self.rows = 0
self.cols = 0
self.n = 0
self.tarStr = []
self.assistMat = []
def conflict(self, k, row, col): # 剪枝衝突檢測
index = row*self.cols+col
if self.rows>row>=0 and self.cols>col>=0 and self.matrix[index]==self.tarStr[k] and not self.assistMat[index]:
return False
else:
return True
def findpath(self, k, row, col):
if k>=self.n: # 搜索到目標字符串 搜索到最底層即爲搜到目標字符串
return True
index = row*self.cols+col # 索引位置
if not self.conflict(k, row, col): # 如果沒衝突,向下搜索
self.assistMat[index] = True # 未衝突向下搜索前,該位置標誌置true 代表搜索過了
if (self.findpath(k+1, row-1, col) or
self.findpath(k+1, row+1, col) or
self.findpath(k+1, row, col-1) or
self.findpath(k+1, row, col+1)): # 向四個方向搜索 任意方向搜索成功即爲成功
return True
self.assistMat[index] = False # 搜索都不成功時回溯並且返回False 搜索同樣失敗
return False
else:
return False # 有衝突直接返回Flase 搜索失敗
def hasPath(self, matrix, rows, cols, path):
self.matrix = matrix
self.rows = rows
self.cols = cols
self.tarStr = path
self.n = len(path)
self.assistMat = [False] * rows * cols # 參數賦值
for i in range(self.rows):
for j in range(self.cols):
if self.findpath(0, i, j): #只要從任意地方開始有搜尋到該目標字符串 則返回 True
return True
return False