File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments