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