Skip to content

Commit 47fcaf5

Browse files
committed
solve number of connected components in an undirected graph
1 parent 8904e80 commit 47fcaf5

File tree

1 file changed

+37
-0
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public class Solution {
2+
public int countComponents(int n, int[][] edges) {
3+
List<List<Integer>> graph = new ArrayList<>();
4+
for (int i = 0; i < n; i++) {
5+
graph.add(new ArrayList<>());
6+
}
7+
for (int[] edge : edges) {
8+
int node = edge[0];
9+
int adj = edge[1];
10+
graph.get(node).add(adj);
11+
graph.get(adj).add(node);
12+
}
13+
14+
int count = 0;
15+
Set<Integer> visited = new HashSet<>();
16+
for (int node = 0; node < n; node++) {
17+
if (visited.contains(node)) {
18+
continue;
19+
}
20+
count++;
21+
Deque<Integer> queue = new ArrayDeque<>();
22+
queue.push(node);
23+
while (!queue.isEmpty()) {
24+
int cur = queue.pop();
25+
if (visited.contains(cur)) continue;
26+
visited.add(cur);
27+
for (int g : graph.get(cur)) {
28+
if (!visited.contains(g)) {
29+
queue.push(g);
30+
}
31+
}
32+
}
33+
}
34+
return count;
35+
}
36+
}
37+

0 commit comments

Comments
 (0)