★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-hsqhqxdx-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1
) is given as graph
.node
graph.length = N
, and j != i
is in the list graph[i]
exactly once, if and only if nodes i
and j
are connected.git
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.github
Example 1:微信
Input: [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3]
Example 2:app
Input: [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3]
Note:spa
1 <= graph.length <= 12
0 <= graph[i].length < graph.length
給出 graph
爲有 N 個節點(編號爲 0, 1, 2, ..., N-1
)的無向連通圖。 code
graph.length = N
,且只有節點 i
和 j
連通時,j != i
在列表 graph[i]
中剛好出現一次。htm
返回可以訪問全部節點的最短路徑的長度。你能夠在任一節點開始和中止,也能夠屢次重訪節點,而且能夠重用邊。blog
示例 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 <= graph.length <= 12
0 <= graph[i].length < graph.length
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 }