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