[Swift]LeetCode847. 访问所有节点的最短路径 | 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:

Input: [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]

Example 2:

Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]

Note:

  1. 1 <= graph.length <= 12
  2. 0 <= graph[i].length < graph.length

给出 graph 为有 N 个节点(编号为 0, 1, 2, ..., N-1)的无向连通图。 

graph.length = N,且只有节点 i 和 j 连通时,j != i 在列表 graph[i] 中恰好出现一次。

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

示例 1:

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

示例 2:

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

提示:

  1. 1 <= graph.length <= 12
  2. 0 <= graph[i].length < graph.length

Runtime: 240 ms
Memory Usage: 19.5 MB
 1 class Solution {
 2     func shortestPathLength(_ graph: [[Int]]) -> Int {
 3         var n:Int = graph.count
 4         var fullMask:Int = (1 << n) - 1
 5         var visited:Set<String> = Set<String>()
 6         var que:[Node] = [Node]()
 7         for i in 0..<n
 8         {
 9             var node:Node = Node(i, 1<<i)
10             que.append(node)
11             visited.insert(node.toString())
12         }
13         var level:Int = 0
14         while(!que.isEmpty)
15         {
16             var size:Int = que.count
17             for i in 0..<size
18             {
19                 var node = que.removeFirst()
20                 if node.mask == fullMask {return level}
21                 for next in graph[node.id]
22                 {
23                     var nextNode:Node = Node(next, node.mask | (1 << next))
24                     if visited.contains(nextNode.toString()) {continue}
25                     que.append(nextNode)
26                     visited.insert(nextNode.toString())
27                 }
28             }
29             level += 1
30         }
31         return level
32     }
33 }
34 
35 class Node {
36     var id:Int = 0
37     var mask:Int = 0
38     
39     init(_ id:Int,_ mask:Int)
40     {
41         self.id = id
42         self.mask = mask        
43     }
44     
45     func toString() -> String
46     {
47         return String(id) + " " + String(mask)
48     }
49 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10591816.html