File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+ class Solution {
4+ static class Node implements Comparable<Node > {
5+ int v, w;
6+
7+ public Node (int v , int w ) {
8+ this . v = v;
9+ this . w = w;
10+ }
11+
12+ @Override
13+ public int compareTo (Node other ) {
14+ return Integer . compare(this . w, other. w);
15+ }
16+ }
17+
18+ public int solution (int N , int [][] road , int K ) {
19+ ArrayList<ArrayList<Node > > graph = new ArrayList<> ();
20+ for (int i = 0 ; i <= N ; i++ ) {
21+ graph. add(new ArrayList<> ());
22+ }
23+
24+ for (int i = 0 ; i < road. length; i++ ) {
25+ int u = road[i][0 ];
26+ int v = road[i][1 ];
27+ int w = road[i][2 ];
28+
29+ graph. get(u). add(new Node (v, w));
30+ graph. get(v). add(new Node (u, w));
31+ }
32+
33+ int [] dist = new int [N + 1 ];
34+ Arrays . fill(dist, Integer . MAX_VALUE );
35+ dist[1 ] = 0 ;
36+
37+ PriorityQueue<Node > q = new PriorityQueue<> ();
38+ q. add(new Node (1 , 0 ));
39+
40+ while (! q. isEmpty()) {
41+ Node current = q. remove();
42+
43+ if (current. w > dist[current. v]) continue ;
44+
45+ for (Node next : graph. get(current. v)) {
46+ int cost = next. w + dist[current. v];
47+
48+ if (cost < dist[next. v]) {
49+ dist[next. v] = cost;
50+ q. add(new Node (next. v, cost));
51+ }
52+ }
53+ }
54+
55+ int answer = 0 ;
56+ for (int i = 1 ; i <= N ; i++ ) {
57+ if (dist[i] <= K ) answer++ ;
58+ }
59+ return answer;
60+ }
61+ }
62+ ```
You can’t perform that action at this time.
0 commit comments