Skip to content

Commit 3b0cd47

Browse files
committed
#263 Number of Connected Components in an Undirected Graph
1 parent 38d5d35 commit 3b0cd47

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
# Time Complexity: O(n)
3+
# Space Comlexity: O(n + m)
4+
- m = edges.length
5+
*/
6+
class Solution {
7+
public int countComponents(int n, int[][] edges) {
8+
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
9+
for (int i = 0; i < n; i++) {
10+
adj.add(new ArrayList<>());
11+
}
12+
for (int i = 0; i < edges.length; i++) {
13+
int a = edges[i][0];
14+
int b = edges[i][1];
15+
adj.get(a).add(b);
16+
adj.get(b).add(a);
17+
}
18+
19+
boolean[] visited = new boolean[n];
20+
int ans = 0;
21+
for (int i = 0; i < n; i++) {
22+
if (visited[i]) continue;
23+
dfs(i, visited, adj);
24+
ans++;
25+
}
26+
27+
return ans;
28+
}
29+
30+
public void dfs(int curr, boolean[] visited, ArrayList<ArrayList<Integer>> adj) {
31+
visited[curr] = true;
32+
33+
for (Integer next : adj.get(curr)) {
34+
if (visited[next]) continue;
35+
dfs(next, visited, adj);
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)