[Swift]LeetCode547. 朋友圈 | Friend Circles
作者:互联网
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:
- N is in range [1,200].
- M[i][i] = 1 for all students.
- 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。
注意:
- N 在[1,200]的范围内。
- 对于所有学生,有M[i][i] = 1。
- 如果有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 let n = matrix.count 23 var numOfCircles = 0 24 var personToCircle = [FriendCircle?](repeating: nil, count: n) 25 26 for column in 0..<n { 27 28 var friends: Set<Int> = [] 29 var circles: Set<FriendCircle> = [] 30 31 for row in 0..<n { 32 if matrix[row][column] == 1 { 33 friends.insert(row) 34 35 if let existingCircle = personToCircle[row] { 36 circles.insert(existingCircle) 37 } 38 } 39 } 40 41 let circle: FriendCircle 42 if circles.count > 1 { 43 for circle in circles { 44 friends.formUnion(circle.friends) 45 } 46 circle = FriendCircle() 47 numOfCircles -= circles.count-1 48 } else if let existingCircle = circles.first { 49 circle = existingCircle 50 } else { 51 circle = FriendCircle() 52 numOfCircles += 1 53 } 54 55 56 for friend in friends { 57 circle.friends.insert(friend) 58 personToCircle[friend] = circle 59 } 60 } 61 return numOfCircles 62 } 63 }
352ms
1 class Solution { 2 3 private var circles: [Int] = [] 4 private var count = 0 5 6 func connect(_ index: Int, _ index2: Int) { 7 let af = find(index) 8 let bf = find(index2) 9 guard af != bf else { 10 return 11 } 12 13 for index in 0..<circles.count { 14 if circles[index] == af { 15 circles[index] = bf 16 } 17 } 18 19 count -= 1 20 } 21 22 func find(_ index: Int) -> Int { 23 if index >= 0 && index < circles.count { 24 return circles[index] 25 } else { 26 return -1 27 } 28 } 29 30 func findCircleNum(_ M: [[Int]]) -> Int { 31 guard !M.isEmpty && !M[0].isEmpty else { 32 return 0 33 } 34 35 count = M.count 36 for index in 0..<M.count { 37 circles.append(index) 38 } 39 40 for row in 0..<M.count { 41 for column in 0..<M[row].count { 42 if row != column && M[row][column] == 1 { 43 connect(row, column) 44 } 45 } 46 } 47 48 return count 49 } 50 }
384ms
1 class Solution { 2 var pre:[Int] 3 init() { 4 self.pre = [Int]() 5 } 6 func findCircleNum(_ M: [[Int]]) -> Int { 7 8 if (M.count > 0) { 9 self.pre = [Int](repeating: 0, count: M.count) 10 for (i, v) in pre.enumerated() { 11 pre[i] = i 12 } 13 for i in 0...M.count - 1 { 14 if (M[i].count == M.count) { 15 for j in 0...M[i].count - 1 { 16 // print("a loop 1") 17 if (M[i][j] == 1) { 18 join(i, j) 19 } 20 } 21 } else { 22 return 0 //异常数据 23 } 24 } 25 var count = 0 26 for (i, v) in pre.enumerated() { 27 if (i == v) { 28 count+=1 29 } 30 } 31 // print("\(count)") 32 return count 33 } 34 return 0 35 } 36 37 func join( _ i:Int, _ j:Int) { 38 var preI = find(i) 39 var preJ = find(j) 40 if (preI != preJ) { 41 self.pre[preI] = preJ 42 } 43 // print("\(self.pre)") 44 } 45 func find(_ i:Int)->Int { 46 var i = i 47 while (self.pre[i] != i) { 48 i = self.pre[i] 49 } 50 return i 51 } 52 }
400ms
1 class Solution { 2 func findCircleNum(_ M: [[Int]]) -> Int { 3 var ret = 0 4 var visited:Array<Bool> = Array(repeating: false, count: M.count) 5 func getFriend(_ y:Int) { 6 for x in 0..<M.count { 7 if !visited[x] && M[y][x] == 1{ 8 visited[y] = true 9 getFriend(x) 10 } 11 } 12 } 13 guard M.count > 0 else { 14 return ret 15 } 16 for y in 0..<M.count { 17 if(!visited[y]) { 18 ret += 1 19 getFriend(y) 20 } 21 } 22 return ret 23 } 24 }
标签:Circles,count,LeetCode547,return,index,Int,朋友圈,func,var 来源: https://www.cnblogs.com/strengthen/p/10414531.html