File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ /**
3
+ * @param n: the number of vertices
4
+ * @param edges: the edges of undirected graph
5
+ * @return : the number of connected components
6
+ */
7
+ const countComponents = function ( n , edges ) {
8
+ // graph 만들기
9
+ const graph = Array . from ( { length : n } ) . map ( ( ) => [ ] ) ;
10
+
11
+ for ( const [ u , v ] of edges ) {
12
+ graph [ u ] . push ( v ) ;
13
+ graph [ v ] . push ( u ) ;
14
+ }
15
+
16
+ // 각 노드 순회하기
17
+ let count = 0 ;
18
+ const visited = new Set ( ) ;
19
+
20
+ for ( let i = 0 ; i < n ; i ++ ) {
21
+ if ( visited . has ( i ) ) {
22
+ continue ;
23
+ }
24
+
25
+ count += 1 ;
26
+
27
+ // bfs
28
+ const queue = [ i ] ;
29
+ visited . add ( i ) ;
30
+
31
+ while ( queue . length ) {
32
+ const u = queue . shift ( ) ;
33
+
34
+ for ( const v of graph [ u ] ) {
35
+ if ( ! visited . has ( v ) ) {
36
+ visited . add ( v ) ;
37
+ queue . push ( v ) ;
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ return count ;
44
+ }
45
+
46
+ // 시간복잡도: O(E)
47
+ // 공간복잡도: O(V)
You can’t perform that action at this time.
0 commit comments