File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // 가중치 있는 무방향 그래프(중복간선 존재)
2+ // 다익스트라 알고리즘 활용
3+ // 1번에서 각 마을로 음식배달. K시간 이하로 배달 가능한 곳 개수 구하기
4+ // 우선순위큐 구현해서 하는 것이 베스트
5+ const solution = ( N , road , K ) => {
6+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] )
7+ for ( let [ a , b , w ] of road ) {
8+ graph [ a ] . push ( [ b , w ] )
9+ graph [ b ] . push ( [ a , w ] )
10+ }
11+
12+ const distance = Array ( N + 1 ) . fill ( Infinity )
13+ distance [ 1 ] = 0
14+
15+ const pq = [ [ 0 , 1 ] ] // [거리, 노드]
16+
17+ while ( pq . length > 0 ) {
18+ const [ dist , cur ] = pq . shift ( )
19+
20+ if ( distance [ cur ] < dist ) continue
21+
22+ for ( const [ next , w ] of graph [ cur ] ) {
23+ const cost = dist + w
24+ if ( cost < distance [ next ] ) {
25+ distance [ next ] = cost
26+ pq . push ( [ cost , next ] )
27+ }
28+ }
29+ }
30+
31+ return distance . filter ( ( dist ) => dist <= K ) . length
32+ }
You can’t perform that action at this time.
0 commit comments