File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ function solution ( n , edge ) {
2
+ // 인접 리스트 = 연결 리스트 이용
3
+ const graph = Array . from ( Array ( n + 1 ) , ( ) => [ ] ) ; // 0이 아닌 1번 부터 시작
4
+ console . log ( graph ) ;
5
+
6
+ // 양방향 그래프 구현
7
+ for ( const [ src , dest ] of edge ) {
8
+ graph [ src ] . push ( dest ) ;
9
+ graph [ dest ] . push ( src ) ;
10
+ }
11
+ console . log ( graph ) ;
12
+
13
+ // 0으로 초기화
14
+ // 각 정점의 거리를 구하는 배열
15
+ const distance = Array ( n + 1 ) . fill ( 0 ) ;
16
+ distance [ 1 ] = 1 ;
17
+
18
+ console . log ( distance ) ;
19
+ // BFS
20
+ const queue = [ 1 ] ; // 1 3 2 6 4 5
21
+ while ( queue . length > 0 ) {
22
+ const src = queue . shift ( ) ; // 매열 첫 요소 제거 후 반환
23
+ for ( const dest of graph [ src ] ) { //src=1 dest=3,2
24
+ // console.log(dest);
25
+ // 한번도 가지 않은 경로 값은 0
26
+ // 0이 아닌 값 = 방문했던 노드 -> 최단 거리를 구하는 것이기 때문에 다시 방문할 필요 없음
27
+ if ( distance [ dest ] === 0 ) { //3->2 2->3 //1->3 1->2
28
+ console . log ( dest ) ;
29
+ queue . push ( dest ) ;
30
+ distance [ dest ] = distance [ src ] + 1 ; // 도착지 = 출발지 + 1 (경로)
31
+ }
32
+ }
33
+ }
34
+
35
+ console . log ( distance ) ;
36
+
37
+ const max = Math . max ( ...distance ) ; // 최대 거리
38
+ console . log ( max ) ; //3
39
+ return distance . filter ( ( item ) => item === max ) . length ; // 최대 거리와 같은 거리를 같은 것의 개수
40
+ }
41
+ solution ( 6 , [
42
+ [ 3 , 6 ] ,
43
+ [ 4 , 3 ] ,
44
+ [ 3 , 2 ] ,
45
+ [ 1 , 3 ] ,
46
+ [ 1 , 2 ] ,
47
+ [ 2 , 4 ] ,
48
+ [ 5 , 2 ] ,
49
+ ] ) ;
You can’t perform that action at this time.
0 commit comments