847 Shortest Path Visiting All Nodes
1. Question
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1
) is given asgraph
.
graph.length = N
, andj != i
is in the list graph[i]
exactly once, if and only if nodesi
andj
are connected.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Example 1:
Example 2:
Note:
1 <= graph.length <= 12
0 <= graph[i].length < graph.length
2. Implementation
(1) BFS + BIt Manipulation
思路: 用Bit Manipulation表示记录已经访问过的node的状态,以每个node作为起点做BFS,找出其中的最短路径即可
3. Time & Space Complexity
时间复杂度O(n * 2^n), n为node的个数,因为我们会尝试从每个node作为起点找最短路径,而从每个node出发,最多会有2^n个状态,所以时间复杂度是n * 2^n, 空间复杂度O(n * 2^n)
Last updated
Was this helpful?