劍指offer 第二版(Python3)--面試題12:矩陣中的路徑

第2章 面試需要的基礎知識

  面試題4:二維數組中的查找

  面試題5:替換空格

  面試題6:從尾到頭打印鏈表

  面試題7:重建二叉樹

  面試題9:用兩個棧實現隊列

  面試題10:斐波那契數列

  面試題11:旋轉數組的最小值

  面試題12:矩陣中的路徑

  面試題15:二進制數中1的個數

第3章 高質量的代碼

第4章 解決面試題的思路

第5章 優化時間和空間效率

第6章 面試中的各項能力

第7章 兩個面試案例


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

做這道題要崩潰了!!!,給的不是矩陣是個字符串!!!遞歸沒遞歸出來!!!各種小錯誤bug!!!

解題思路

  1. 先找到矩陣中與第一個字符相同的點;
  2. 從該點開始深度優先搜索。

實戰

class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        def dfs(x, y, path):
            if not path:
                return True
            index = x * cols + y
            if x < 0 or x >= rows or y < 0 or y >= cols or visited[index]:
                return False
            if matrix[index] != path[0]:
                return False
            visited[index] = 1
            if (dfs(x-1, y, path[1:]) or
                dfs(x, y+1, path[1:]) or
                dfs(x, y-1, path[1:]) or
                dfs(x+1, y, path[1:])):
                return True
            visited[index] = 0
            return False
        
        for i in range(rows):
            for j in range(cols):
                if matrix[i*cols+j] == path[0]:
                    visited = [0] * rows * cols
                    exist = dfs(i, j, path)
                    if exist: return True
        return False

靜下心來做,好像也不用很久。。。回溯過程和上面稍有不同

class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        if not matrix or not path:
            return False
        def recc(string, point):
            if not string:
                return True
            px, py = point[0], point[1]
            for d in direction:
                x, y = px + d[0], py + d[1]
                index = y*cols + x
                if index < 0 or index >= rows * cols or visited[index]:
                    continue
                visited[index] = True
                if string[0] == matrix[index]:
                    flag = recc(string[1:], (x, y))
                    if flag:
                        return True
                visited[index] = False
            return False
        
        direction = [(-1, 0), (0, 1), (1, 0), (0, -1)]
        
        for row in range(rows):
            for col in range(cols):
                if matrix[row*cols + col] == path[0]:
                    visited = [False] * rows * cols
                    visited[row*cols + col] = True
                    flag = recc(path[1:], (col, row))
                    if flag:
                        return True
        return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章