-
Notifications
You must be signed in to change notification settings - Fork 112
/
0547-FriendCircles.cs
57 lines (47 loc) · 1.42 KB
/
0547-FriendCircles.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//-----------------------------------------------------------------------------
// Runtime: 112ms
// Memory Usage: 28.3 MB
// Link: https://leetcode.com/submissions/detail/375119712/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0547_FriendCircles
{
public int FindCircleNum(int[][] M)
{
var N = M.Length;
var uf = new UnionFind(N);
for (int i = 0; i < N; i++)
for (int j = 0; j < i; j++)
if (M[i][j] == 1)
uf.Union(i, j);
return uf.Count;
}
public class UnionFind
{
private int[] parents;
public UnionFind(int N)
{
parents = new int[N];
for (int i = 0; i < N; i++)
parents[i] = i;
Count = N;
}
public int Count { get; set; }
public int Find(int i)
{
if (parents[i] != i)
parents[i] = Find(parents[i]);
return parents[i];
}
public void Union(int i, int j)
{
var index1 = Find(i);
var index2 = Find(j);
if (index1 == index2) return;
parents[index1] = index2;
Count--;
}
}
}
}