Leetcode 面試題 04.01.節點間通路

Leetcode 面試題 04.01.節點間通路

1 題目描述(Leetcode題目鏈接

  節點間通路。給定有向圖,設計一個算法,找出兩個節點之間是否存在一條路徑。

 輸入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
 輸出:true
 輸入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
 輸出 true

提示:

  • 節點數量n在[0, 1e5]範圍內。
  • 節點編號大於等於 0 小於 n。
  • 圖中可能存在自環和平行邊。

2 題解

  圖的深度優先搜索或廣度優先搜索都可以做,先構建鄰接表,把自環和平行邊都去掉,然後從start進行深度優先搜索,使用color表示節點的訪問情況。0,1,2分別表示未訪問,正在訪問,訪問完畢。

class Solution:
    def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
        Adj = collections.defaultdict(list)
        for u, v in graph:
            if u != v and v not in Adj[u]:
                Adj[u].append(v)

        color = [0]*n 

        def dfs(u):
            color[u] = 1
            for v in Adj[u]:
                if color[v] == 0:
                    dfs(v)
            color[u] = 2

        dfs(start)
        return color[target] != 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章