8
8
public class _1334 {
9
9
public static class Solution1 {
10
10
/**
11
- * Dijakstra's algorithm to find the shortest path from each node to all possibly reachable nodes within limit.
11
+ * Dijkstra's algorithm to find the shortest path from each node to all possibly reachable nodes within limit.
12
+ * Dijkstra's algorithm applies to weights are non-negative problems.
12
13
* Keys to implement Dijkstra's algorithm:
13
14
* 1. use an array to hold the shortest distance to each node for each node;
14
15
* 2. initially, only the starting node distance is zero, all other nodes' distances to be infinity;
15
16
* 3. use a PriorityQueue to poll out the next node that has the shortest distance and scan through all its neighbors,
16
- * if the cost can be updated, then put it into the priority queue
17
+ * if the cost can be updated, then put it into the priority queue (this is a critical key to implement Dijkstra!)
18
+ * Only when this node's code could be updated/shortened, we'll put it into the priority queue/minHeap,
19
+ * so that next time, it'll be polled and processed based on priority order
17
20
*/
18
21
public int findTheCity (int n , int [][] edges , int distanceThreshold ) {
19
22
List <List <int []>> graph = new ArrayList ();
@@ -31,21 +34,21 @@ public int findTheCity(int n, int[][] edges, int distanceThreshold) {
31
34
for (int i = 0 ; i < n ; i ++) {
32
35
dijkstraAlgo (graph , i , shortestPaths [i ]);
33
36
}
34
- return findCity (shortestPaths , distanceThreshold );
37
+ return findCityWithFewestReachableCities (shortestPaths , distanceThreshold );
35
38
}
36
39
37
- private int findCity (int [][] shortestPaths , int distanceThreshold ) {
40
+ private int findCityWithFewestReachableCities (int [][] shortestPaths , int distanceThreshold ) {
38
41
int ans = 0 ;
39
- int fewestConnected = shortestPaths .length ;
42
+ int fewestReachable = shortestPaths .length ;
40
43
for (int i = 0 ; i < shortestPaths .length ; i ++) {
41
44
int reachable = 0 ;
42
45
for (int j = 0 ; j < shortestPaths [0 ].length ; j ++) {
43
46
if (i != j && shortestPaths [i ][j ] <= distanceThreshold ) {
44
47
reachable ++;
45
48
}
46
49
}
47
- if (reachable <= fewestConnected ) {
48
- fewestConnected = reachable ;
50
+ if (reachable <= fewestReachable ) {
51
+ fewestReachable = reachable ;
49
52
ans = i ;
50
53
}
51
54
}
0 commit comments