Description#
You have a graph of n
nodes. You are given an integer n
and an array edges
where edges[i] = [ai, bi]
indicates that there is an edge between ai
and bi
in the graph.
Return the number of connected components in the graph.
Example 1:
![](https://spcdn.pages.dev/leetcode/problems/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn1-graph.jpg)
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Example 2:
![](https://spcdn.pages.dev/leetcode/problems/0323.Number%20of%20Connected%20Components%20in%20an%20Undirected%20Graph/images/conn2-graph.jpg)
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
Constraints:
1 <= n <= 2000
1 <= edges.length <= 5000
edges[i].length == 2
0 <= ai <= bi < n
ai != bi
- There are no repeated edges.
Solutions#
Solution 1#
1
2
3
4
5
6
7
8
9
10
11
| class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(n))
for a, b in edges:
p[find(a)] = find(b)
return sum(i == find(i) for i in range(n))
|
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
| class Solution {
private int[] p;
public int countComponents(int n, int[][] edges) {
p = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
}
for (int[] e : edges) {
int a = e[0], b = e[1];
p[find(a)] = find(b);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
if (i == find(i)) {
++ans;
}
}
return ans;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<int> p(n);
iota(p.begin(), p.end(), 0);
for (int i = 0; i < n; ++i) p[i] = i;
function<int(int)> find = [&](int x) -> int {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
};
for (auto& e : edges) {
int a = e[0], b = e[1];
p[find(a)] = find(b);
}
int ans = 0;
for (int i = 0; i < n; ++i) ans += i == find(i);
return ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| func countComponents(n int, edges [][]int) (ans int) {
p := make([]int, n)
for i := range p {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
for _, e := range edges {
a, b := e[0], e[1]
p[find(a)] = find(b)
}
for i := 0; i < n; i++ {
if i == find(i) {
ans++
}
}
return
}
|
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
| /**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/
var countComponents = function (n, edges) {
let p = new Array(n);
for (let i = 0; i < n; ++i) {
p[i] = i;
}
function find(x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
for (const [a, b] of edges) {
p[find(a)] = find(b);
}
let ans = 0;
for (let i = 0; i < n; ++i) {
if (i == find(i)) {
++ans;
}
}
return ans;
};
|