[Swift]LeetCode323. 無向圖中的連通區域的個數 $ Number of Connected Components in an Undirected Graph

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-fpwgtokp-ke.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.node

Example 1:git

     0          3github

     |          |微信

     1 --- 2    4app

Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.函數

Example 2:測試

     0           4spa

     |           |code

     1 --- 2 --- 3

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.

 Note:

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.


給定n個標記爲0到n-1的節點和無向邊列表(每一個邊都是一對節點),編寫一個函數來查找無向圖中鏈接的組件的數量。

例1:

     0          3

     |          |

     1 --- 2    4

假設n=5,edges = [[0, 1], [1, 2], [3, 4]],返回2。

例2:

     0           4

     |           |

     1 --- 2 --- 3

若是n=5,edges = [[0, 1], [1, 2], [2, 3], [3, 4]],返回1。

注:

能夠假定邊中不會出現重複的邊。由於全部邊都是無向的,[0,1]與[1,0]相同,所以不會出如今邊中。


Solution:

 1 class Solution {
 2     func countComponents(_ n:Int,_ edges:inout [[Int]]) -> Int {
 3         var res:Int = n
 4         var root:[Int] = [Int](repeating:0,count:n)
 5         for i in 0..<n
 6         {
 7             root[i] = i
 8         }
 9         for a in edges
10         {
11             var x:Int = find(&root, a[0])
12             var y:Int = find(&root, a[1])
13             if x != y
14             {
15                 res -= 1
16                 root[y] = x
17             }
18         }
19         return res
20     }
21     
22     func find(_ root:inout [Int],_ i:Int) -> Int
23     {
24         var i = i
25         while(root[i] != i)
26         {
27             i = root[i]
28         }
29         return i
30     }
31 }

點擊:Playground測試

1 let n1:Int = 5
2 var edge1:[[Int]] = [[0, 1], [1, 2], [3, 4]]
3 print(Solution().countComponents(n1,&edge1))
4 //Print 2
5 let n2:Int = 5
6 var edge2:[[Int]] = [[0, 1], [1, 2], [2, 3], [3, 4]]
7 print(Solution().countComponents(n2,&edge2))
8 //Print 1
相關文章
相關標籤/搜索