File tree Expand file tree Collapse file tree
src/kyu9341/programmers_네트워크 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const initArray = ( size , val = null ) => Array . from ( { length : size } , ( ) => val ) ;
2+ const initArrayInArray = size =>
3+ Array . from ( { length : size } , ( ) => new Array ( ) ) ;
4+
5+ const solution = ( n , computers ) => {
6+ const network = initArrayInArray ( n ) ;
7+ const check = initArray ( n , false ) ;
8+
9+ computers . forEach ( ( row , rowIdx ) => {
10+ row . forEach ( ( computer , colIdx ) => {
11+ if ( rowIdx !== colIdx && computer ) network [ rowIdx ] . push ( colIdx ) ;
12+ } ) ;
13+ } ) ;
14+
15+ const dfs = ( node , network ) => {
16+ check [ node ] = true ;
17+
18+ network [ node ] . forEach ( ( _ , computer ) => {
19+ const next = network [ node ] [ computer ] ;
20+ if ( ! check [ next ] ) dfs ( next , network ) ;
21+ } ) ;
22+ } ;
23+
24+ const answer = network . reduce ( ( acc , _ , computer ) => {
25+ if ( ! check [ computer ] ) {
26+ dfs ( computer , network ) ;
27+ return acc + 1 ;
28+ }
29+ return acc ;
30+ } , 0 ) ;
31+
32+ return answer ;
33+ } ;
34+
35+ ( ( ) => {
36+ const inputs = [
37+ [
38+ [ 1 , 1 , 0 ] ,
39+ [ 1 , 1 , 0 ] ,
40+ [ 0 , 0 , 1 ] ,
41+ ] ,
42+ [
43+ [ 1 , 1 , 0 ] ,
44+ [ 1 , 1 , 1 ] ,
45+ [ 0 , 1 , 1 ] ,
46+ ] ,
47+ ] ;
48+
49+ inputs . forEach ( input => console . log ( solution ( input . length , input ) ) ) ;
50+ } ) ( ) ;
You can’t perform that action at this time.
0 commit comments