Skip to content

Commit eda7ce0

Browse files
committed
Number Of Connected Components In An Undirected Graph
1 parent a14bddf commit eda7ce0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// TC: O(n + m)
2+
// n = the number of nodes, m = the number of edges
3+
// SC: O(n + m)
4+
// n, m are the each size of the 2 demension array 'edges'
5+
public class Solution {
6+
public int countComponents(int n, int[][] edges) {
7+
List<List<Integer>> graph = new ArrayList<>();
8+
9+
for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
10+
11+
for (int[] edge : edges) {
12+
graph.get(edge[0]).add(edge[1]);
13+
graph.get(edge[1]).add(edge[0]);
14+
}
15+
16+
boolean[] visit = new boolean[n];
17+
int count = 0;
18+
19+
for (int i = 0; i < n; i++) {
20+
if (!visit[i]) {
21+
count += 1;
22+
dfs(i, graph, visit);
23+
}
24+
}
25+
return count;
26+
}
27+
28+
private void dfs(int node, List<List<Integer>> graph, boolean[] visit) {
29+
visit[node] = true;
30+
for (int neighbor : graph.get(node)) {
31+
if (!visit[neighbor]) dfs(neighbor, graph, visit);
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)