leetcode-847-Shortest Path Visiting All Nodes
问题
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph.
graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j 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:
1 | Input: [[1,2,3],[0],[0],[0]] |
Example 2:
1 | Input: [[1],[0,2,4],[1,3,4],[2],[1,2]] |
Note:
1 <= graph.length <= 120 <= graph[i].length < graph.length
分析
每个阶段的状态保存需要有两个部分来表示,一个是需要保存所有已经访问过的节点有哪些,另一个是最终停在了哪一个节点上。保存已经访问过的节点可是使用二进制位压缩来表示,比如节点0,2,3被访问,可以表示为二进制 1101。于是我们使用二维数组来表示状态,第一维表示当前节点的位置,第二位来表示已经访问过的节点的有哪些。使用广度优先搜索,来从初始状态逐渐推向整个状态,visited[n][1<<n] 用来标记状态是否已经被遍历过。
note:之前一直想的是DFS,没有想到BFS也有和DP相结合的情况。
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/04/04/leetcode-847/
License: 知识共享署名-非商业性使用 4.0 国际许可协议