LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

847. 访问所有节点的最短路径

存在一个由 n 个节点组成的无向连通图,图中的节点按从 0n - 1 编号。

给你一个数组 graph 表示这个图。其中,graph[i] 是一个列表,由所有与节点 i 直接相连的节点组成。

返回能够访问所有节点的最短路径的长度。你可以在任一节点开始和停止,也可以多次重访节点,并且可以重用边。

示例 1:

img

输入:graph = [[1,2,3],[0],[0],[0]]
输出:4
解释:一种可能的路径为 [1,0,2,0,3]

示例 2:

img

输入:graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
输出:4
解释:一种可能的路径为 [0,1,4,2,3]

提示:

BFS 困难

BFS遍历时,检测遍历状态,并且利用(cur, status)防止重复访问

代码

class Solution:
    def shortestPathLength(self, graph: List[List[int]]) -> int:
        n = len(graph)
        q = deque([ (i, 1 << i) for i in range(n)])
        visited = set(q)
        step = 0
        while q:
            nq = len(q)
            for _ in range(nq):
                cur, status = q.popleft()
                for nei in graph[cur]:
                    new_status = status | (1 << nei)
                    if new_status == ((1 << n)-1):
                        return step + 1
                    if (nei,new_status) not in visited:
                        visited.add((nei, new_status))
                        q.append((nei, new_status))
            step += 1
        return 0