劍指offer 65. 矩陣中的路徑
阿新 • • 發佈:2018-11-29
題目描述
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
思路:
優化版回溯法
- 將matrix字串模擬對映為一個字元矩陣(但並不實際建立一個矩陣)
- 取一個boolean[matrix.length]標記某個字元是否已經被訪問過,用一個布林矩陣進行是否存在該數值的標記。
- 如果沒找到結果,需要將對應的boolean標記值置回false,返回上一層進行其他分路的查詢。
參考答案:
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if not matrix and rows <= 0 and cols <= 0 and path == None:
return False
# 模擬的字元矩陣
markmatrix = [0] * (rows * cols)
pathlength = 0
# 從第一個開始遞迴,當然第一二個字元可能並不位於字串之上,所以有這樣一個雙層迴圈找起點用的,一旦找到第一個符合的字串,就開始進入遞迴,
# 返回的第一個return Ture就直接跳出迴圈了。
for row in range(rows):
for col in range(cols):
if self.hasPathCore(matrix, rows, cols, row, col, path, pathlength, markmatrix):
return True
return False
def hasPathCore(self, matrix, rows, cols, row, col, path, pathlength, markmatrix):
# 說明已經找到該路徑,可以返回True
if len(path) == pathlength:
return True
hasPath = False
if row >= 0 and row < rows and col >= 0 and col < cols and matrix[row * cols + col] == path[pathlength] and not \
markmatrix[row * cols + col]:
pathlength += 1
markmatrix[row * cols + col] = True
# 進行該值上下左右的遞迴
hasPath = self.hasPathCore(matrix, rows, cols, row - 1, col, path, pathlength, markmatrix) \
or self.hasPathCore(matrix, rows, cols, row, col - 1, path, pathlength, markmatrix) \
or self.hasPathCore(matrix, rows, cols, row + 1, col, path, pathlength, markmatrix) \
or self.hasPathCore(matrix, rows, cols, row, col + 1, path, pathlength, markmatrix)
# 對標記矩陣進行布林值標記
if not hasPath:
pathlength -= 1
markmatrix[row * cols + col] = False
return hasPath
Note
- 這種找路徑尤其表明不能走回頭路的題,往往需要結合一個標記矩陣用於標識該矩陣對應元素是否為已經遍歷過了,如果變數過了,則不能再進行重複遍歷。