File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ ⭐️ 문제 정보 ⭐️
3+ 문제 : 49189 - 가장 먼 노드
4+ 레벨 : Level 3
5+ 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/49189
6+ */
7+
8+ // ANCHOR : 26.02.04 풀이
9+ /**
10+ APPROACH:
11+ 하나의 노드에서 다른 노드"들"까지의 최단경로를 구해야 하는 문제이기 때문에 다익스트라 알고리즘을 먼저 생각했었음.
12+ 하지만 이 문제는 모든 간선의 가중치가 1로 동일하기 때문에 다익스트라를 쓰지 않고 BFS만으로도 각 노드까지의 최단거리를 구할 수 있다.
13+ */
14+ function solution ( n , edge ) {
15+ const adj = Array . from ( { length : n + 1 } , ( ) => [ ] ) ;
16+ for ( const [ a , b ] of edge ) {
17+ adj [ a ] . push ( b ) ;
18+ adj [ b ] . push ( a ) ;
19+ }
20+
21+ // -1은 아직 모르는 거리를 의미함
22+ // NOTE : BFS에서는 첫 방문 거리가 곧 최단거리이므로 (다익스트라처럼 갱신 x) Infinity 대신 -1을 쓴다.
23+ const dist = Array . from ( { length : n + 1 } , ( ) => - 1 ) ;
24+
25+ // BFS 시작
26+ dist [ 1 ] = 0 ; // 시작 지점
27+ const queue = [ 1 ] ;
28+ let head = 0 ;
29+ while ( head < queue . length ) {
30+ const front = queue [ head ++ ] ;
31+ const neighbors = adj [ front ] ;
32+ if ( neighbors . length === 0 ) continue ;
33+
34+ neighbors . forEach ( ( neighbor ) => {
35+ if ( dist [ neighbor ] !== - 1 ) return ;
36+ // 처음 방문하는 시점이 바로 최단거리이므로 주저없이 업데이트
37+ // 방문 기록은 겸사겸사
38+ dist [ neighbor ] = dist [ front ] + 1 ;
39+ queue . push ( neighbor ) ;
40+ } ) ;
41+ }
42+
43+ const maxDist = Math . max ( ...dist ) ;
44+ const answer = dist . filter ( ( d ) => d === maxDist ) . length ;
45+ return answer ;
46+ }
Original file line number Diff line number Diff line change 4242| 42888 | 오픈채팅방 | [ 42888_오픈채팅방.js] ( Level2/42888_오픈채팅방.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/42888 ) |
4343| 42889 | 실패율 | [ 42889_실패율.js] ( Level1/42889_실패율.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/42889 ) |
4444| 43162 | 네트워크 | [ 43162_네트워크.js] ( Level3/43162_네트워크.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/43162 ) |
45+ | 49189 | 가장 먼 노드 | [ 49189_가장_먼_노드.js] ( Level3/49189_가장_먼_노드.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/49189 ) |
4546| 49993 | 스킬트리 | [ 49993_스킬트리.js] ( Level2/49993_스킬트리.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/49993 ) |
4647| 49994 | 방문 길이 | [ 49994_방문_길이.js] ( Level2/49994_방문_길이.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/49994 ) |
4748| 60057 | 문자열 압축 | [ 60057_문자열_압축.js] ( Level2/60057_문자열_압축.js ) | [ 🔗] ( https://school.programmers.co.kr/learn/courses/30/lessons/60057 ) |
You can’t perform that action at this time.
0 commit comments