File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ function solution ( N , road , K ) {
2+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] ) ;
3+
4+ for ( const [ a , b , c ] of road ) {
5+ graph [ a ] . push ( [ b , c ] ) ;
6+ graph [ b ] . push ( [ a , c ] ) ;
7+ }
8+
9+ const distances = Array ( N + 1 ) . fill ( Infinity ) ;
10+ distances [ 1 ] = 0 ;
11+ const priorityQueue = [ [ 0 , 1 ] ] ;
12+
13+ while ( priorityQueue . length > 0 ) {
14+ const [ currentDistance , currentNode ] = priorityQueue . shift ( ) ;
15+
16+ if ( currentDistance > distances [ currentNode ] ) {
17+ continue ;
18+ }
19+
20+ for ( const [ neighbor , time ] of graph [ currentNode ] ) {
21+ const newDistance = currentDistance + time ;
22+ if ( newDistance < distances [ neighbor ] ) {
23+ distances [ neighbor ] = newDistance ;
24+ priorityQueue . push ( [ newDistance , neighbor ] ) ;
25+ priorityQueue . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
26+ }
27+ }
28+ }
29+
30+ return distances . filter ( ( distance ) => distance <= K ) . length ;
31+ }
You can’t perform that action at this time.
0 commit comments