• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode547.朋友圈|FriendCircles

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10414531.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a directfriend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are directfriends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

Input: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. 
The 2nd student himself is in a friend circle. So return 2. 

Example 2:

Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, 
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Note:

  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.
  3. If M[i][j] = 1, then M[j][i] = 1.

班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。

给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。

示例 1:

输入: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
输出: 2 
说明:已知学生0和学生1互为朋友,他们在一个朋友圈。
第2个学生自己在一个朋友圈。所以返回2。

示例 2:

输入: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
输出: 1
说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。

注意:

  1. N 在[1,200]的范围内。
  2. 对于所有学生,有M[i][i] = 1。
  3. 如果有M[i][j] = 1,则有M[j][i] = 1。

180ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         var count = 0
 4         var visited: [Int] = [Int](repeating: 0, count: M.count)
 5         for i in 0...(M.count - 1) {
 6             if visited[i] == 0 {
 7                 self.dfs(M, &visited, i)
 8                 count += 1
 9             }
10         }
11         
12         return count
13     }
14     
15     func dfs(_ M : [[Int]], _ visited: inout [Int], _ i: Int){
16         
17         for j in 0...(M.count  - 1) {
18             if M[i][j] == 1 && visited[j] == 0 {
19                 visited[j] = 1
20                 dfs(M, &visited, j)
21             }
22         }
23     }    
24 }

Runtime: 184 ms
Memory Usage: 19 MB
 1 class Solution {
 2     //经典思路:联合查找Union Find
 3     func findCircleNum(_ M: [[Int]]) -> Int {
 4         var n:Int = M.count
 5         var res:Int = n
 6         var root:[Int] = [Int](repeating:0,count:n)
 7         for i in 0..<n
 8         {
 9             root[i] = i
10         }
11         for i in 0..<n
12         {
13             for j in (i + 1)..<n
14             {
15                 if M[i][j] == 1
16                 {
17                     var p1:Int = getRoot(&root, i)
18                     var p2:Int = getRoot(&root, j)
19                     if p1 != p2
20                     {
21                         res -= 1
22                         root[p2] = p1                        
23                     }
24                 }
25                 
26             }
27         }
28         return res
29     }
30     
31     func getRoot(_ root:inout [Int],_ i:Int) -> Int
32     {
33         var i = i
34         while(i != root[i])
35         {
36             root[i] = root[root[i]]
37             i = root[i]
38         }
39         return i
40     }
41 }

184ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         var ans = 0
 4         
 5         let size = M.count
 6         var visited = [Bool].init(repeating: false, count: size)
 7         var current = 0
 8         func DFS(_ cur: Int) {
 9             guard !visited[cur] else {
10                 return
11             }
12             visited[cur] = true
13             for i in 0 ..< size {
14                 if !visited[i] && M[cur][i] == 1 {
15                     DFS(i)
16                 }
17             }
18         }
19         for i in 0 ..< size where !visited[i] {
20             ans += 1
21             DFS(i)
22         }
23         return ans
24     }
25 }

188ms

 1 class Solution {
 2     func findCircleNum(_ matrix: [[Int]]) -> Int {
 3         guard !matrix.isEmpty else {
 4             return 0
 5         }
 6         
 7         let n = matrix.count
 8         
 9         var visitedStudents = [Bool](repeating: false, count: n)
10         var numOfCircles = 0
11         
12         for student in 0..<n {
13             if visitedStudents[student] {
14                 continue
15             }
16             
17             numOfCircles += 1
18             visitFriends(student: student, matrix: matrix, visitedStudents: &visitedStudents)
19         }
20         
21         return numOfCircles
22     }
23     
24     func visitFriends(student: Int, matrix: [[Int]], visitedStudents: inout [Bool]) {
25         visitedStudents[student] = true
26         
27         for friend in 0..<matrix.count {
28             guard matrix[student][friend] == 1 else {
29                 continue
30             }
31             guard !visitedStudents[friend] else {
32                 continue
33             }
34             
35             visitFriends(student: friend, matrix: matrix, visitedStudents: &visitedStudents)
36         }
37     }
38 }

192ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         var visited = Set<Int>()
 4         var num = 0
 5         for i in 0..<M.count {
 6             if !visited.contains(i) {
 7                 self.recurse(i, M, &visited)
 8                 num += 1
 9             }
10         }
11         return num
12     }
13     
14     func recurse(_ node: Int, _ graph: [[Int]], _ visited: inout Set<Int>) {
15         visited.insert(node)
16         for i in 0..<graph.count {
17             if !visited.contains(i) && graph[node][i] > 0 {
18                 recurse(i, graph, &visited)
19             }
20         }
21     }
22 }

196ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         guard M.count > 0 && M[0].count > 0 else {
 4             return 0
 5         }
 6         
 7         var unionFind = UnionFind<Int>()
 8         
 9         for row in 0..<M.count {
10             for column in 0..<M[row].count {
11                 if M[row][column] == 1 {
12                     unionFind.addSet(row)
13                     unionFind.addSet(column)
14                     unionFind.union(row, column)
15                 }
16             }
17         }
18         
19         return unionFind.numerOfSets
20     }
21 }
22 
23 
24 public struct UnionFind<T: Hashable> {
25     private var index: [T: Int] = [:]
26     private var parent: [Int] = []
27     private var size: [Int] = []
28     public var numerOfSets: Int = 0 
29     
30     public mutating func addSet(_ element: T) {
31         if index[element] == nil {
32             index[element] = parent.count
33             parent.append(parent.count)
34             size.append(1)
35             numerOfSets += 1
36         }
37     }
38     
39     public mutating func find(_ element: T) ->Int? {
40         guard let index = index[element] else {
41             return nil 
42         }
43         return setByIndex(index)
44     }
45     
46     private mutating func setByIndex(_ index: Int) -> Int {
47         if parent[index] == index {
48             return index 
49         } else {
50             parent[index] = setByIndex(parent[index])
51             return parent[index]
52         }
53     }
54     
55     public mutating func union(_ element1: T, _ element2: T) {
56         guard let set1 = find(element1), let set2 = find(element2) else {
57             return 
58         }
59         
60         if set1 != set2 {
61             numerOfSets -= 1 
62             if size[set1] > size[set2] {
63                 parent[set2] = set1 
64                 size[set1] += size[set2]
65             } else {
66                 parent[set1] = set2 
67                 size[set2] += size[set1]
68             }
69         }
70     }
71 }

200ms

 1 class Solution {
 2     class UnionFind {
 3         private var parent: [Int]
 4         private (set) var count = 0
 5         
 6         init(size: Int, count: Int) {
 7             self.parent = Array(0..<size)
 8             self.count = count
 9         }
10 
11         func union(_ x: Int, _ y: Int) {
12             let px = find(x)
13             let py = find(y)
14             if px != py {
15                 parent[px] = py
16                 count -= 1
17             }
18         }
19 
20         func find(_ x: Int) -> Int {
21             if parent[x] == x {
22                 return x
23             }
24             parent[x] = find(parent[x])
25             return parent[x]
26         }
27     }
28 
29     func findCircleNum(_ M: [[Int]]) -> Int {
30         if M.isEmpty || M[0].isEmpty {
31             return 0
32         }
33 
34         let n = M.count
35         let unionFind = UnionFind(size: n, count: n)
36 
37         for y in 0..<n {
38             for x in 0..<n {
39                 if x != y, M[y][x] == 1 {
40                     unionFind.union(x, y)
41                 }
42             }
43         }
44         return unionFind.count
45     }
46 }

212ms

 1 class UnionFind {
 2     private var connectivities: [Int]
 3     private var sizes: [Int]
 4     init(size: Int) {
 5         self.connectivities = [Int](repeating: 0, count: size)
 6         self.sizes = [Int](repeating: 1, count: size)
 7         for i in 0..<size {
 8             connectivities[i] = i
 9         }
10     }
11     func connect(n1: Int, n2: Int) {
12         guard let root1 = root(of: n1),
13             let root2 = root(of: n2),
14             root1 != root2 else { return }
15         let sz1 = sizes[root1]
16         let sz2 = sizes[root2]
17         if sz1 > sz2 {
18             connectivities[root2] = root1
19             sizes[root1] += sizes[root2]
20         } else {
21             connectivities[root1] = root2
22             sizes[root2] += sizes[root1]
23         }
24     }
25     func isConnected(n1: Int, n2: Int) -> Bool {
26         return root(of: n1) == root(of: n2)
27     }
28     func root(of n: Int) -> Int? {
29         guard n < connectivities.count else { return nil }
30         let parent = connectivities[n]
31         if parent == n {
32             return n
33         }
34         guard let rt = root(of: parent) else { return nil }
35         connectivities[n] = rt
36         return rt
37     }
38     func snapshot() {
39         print("c: \(connectivities)")
40         print("s: \(sizes)")
41     }
42 }
43 
44 class Solution {
45     func findCircleNum(_ M: [[Int]]) -> Int {
46         let size = M.count
47         let uf = UnionFind(size: size)
48         for (y, row) in M.enumerated() {
49             for (x, _) in row.enumerated() {
50                 if x <= y {
51                     continue
52                 }
53                 if M[y][x] == 1 {
54                     uf.connect(n1: y, n2: x)
55                 }
56             }
57         }
58         var groupSet = Set<Int>()
59         for i in 0..<M.count {
60             guard let root = uf.root(of: i) else { continue }
61             groupSet.insert(root)
62         }
63         return groupSet.count
64     }
65 }

216ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         var visited: Set<Int> = Set<Int>()
 4         var res = 0
 5         var q: [Int] = []
 6         for i in 0..<M.count {
 7             if !visited.contains(i) {
 8                 res += 1
 9                 q.append(i)
10                 while !q.isEmpty {
11                     let friend = q.removeFirst()
12                     if !visited.contains(friend) {
13                         visited.insert(friend)
14                         for j in 0..<M[friend].count {
15                             if M[friend][j] == 1 {
16                                 q.append(j)
17                             }
18                         }
19                     }
20                 }
21             }
22         }
23         return res
24     }
25 }

228ms

 1 class Solution {
 2     func findCircleNum(_ M: [[Int]]) -> Int {
 3         
 4         var sum = 0
 5         var circle = M
 6         let mCount = M.count
 7         for i in 0 ..< mCount {
 8             let isCircle = p_circle(&circle, down: i, right: i, s: mCount)
 9             if isCircle {  sum += 1 }
10         }
11         return sum
12     }
13     
14     func p_circle(_ circle: inout [[Int]], down: Int, right: Int, s: Int) -> Bool {
15         guard
16             down < s,
17             right <= down,
18             circle[down][right] == 1
19             else { return false }
20         circle[down][right] = 0
21         circle[right][down] = 0
22 
23         var r = 0
24         if down == 0 { r = 1 }
25         while (r < s) {
26             if circle[down][r] == 1 {
27                 _ = p_circle(&circle, down: r, right: r, s: s)
28             }
29             r += 1
30             if down == r { r += 1 }
31         }
32         return true
33     }
34 }

328ms

 1 class FriendCircle {
 2     var friends: Set<Int> = []
 3 }
 4 
 5 extension FriendCircle: Hashable {
 6     var hashValue: Int {
 7         return ObjectIdentifier(self).hashValue
 8     }
 9     
10     static func ==(lhs: FriendCircle, rhs: FriendCircle) -> Bool {
11         return lhs === rhs
12     }
13 }
14 
15 
16 class Solution {
17     func findCircleNum(_ matrix: [[Int]]) -> Int {
18         guard !matrix.isEmpty else {
19             return 0
20         }
21         
22    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Ubuntu配置Swift开发环境发布时间:2022-07-13
下一篇:
[Swift]LeetCode553.最优除法|OptimalDivision发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap