劍指offer算法題【11】:矩陣中的路徑(Python實現)

一. 題目

   請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如[a,b,t,g,c,f,c,s,j,d,e,h 矩陣中包含一條字符串"bfce"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。

二. 思路(回溯法)

  1.將matrix字符串模擬映射爲一個字符矩陣(但並不實際創建一個矩陣)
  2.取一個boolean[matrix.length]標記某個字符是否已經被訪問過,用一個布爾矩陣進行是否存在該數值的標記。
  3.如果沒找到結果,需要將對應的boolean標記值置回false,返回上一層進行其他分路的查找。

三. 代碼

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)

            # 對標記矩陣進行布爾值標記,如果當前層的下一層都沒有我們要的,那麼就要退回到上一層,這個時候pathlength要減1
            if not hasPath:
                pathlength -= 1
                markmatrix[row * cols + col] = False
        return hasPath

if __name__ == '__main__':
    matrix = ['a','b','t','g','c','f','c','s','j','d','e','h']
    rows = 3
    cols = 4
    path = ['b','f','c','e']
    path1 = ['a','b','f','b']
    ss = Solution()
    print(ss.hasPath(matrix,rows,cols,path))
    print(ss.hasPath(matrix, rows, cols, path1))

運行結果:

發佈了234 篇原創文章 · 獲贊 71 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章