Skip to content

Commit dcf570b

Browse files
add comments for 1334
1 parent 84e46d6 commit dcf570b

File tree

1 file changed

+10
-7
lines changed
  • src/main/java/com/fishercoder/solutions/secondthousand

1 file changed

+10
-7
lines changed

Diff for: src/main/java/com/fishercoder/solutions/secondthousand/_1334.java

+10-7
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@
88
public class _1334 {
99
public static class Solution1 {
1010
/**
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.
1213
* Keys to implement Dijkstra's algorithm:
1314
* 1. use an array to hold the shortest distance to each node for each node;
1415
* 2. initially, only the starting node distance is zero, all other nodes' distances to be infinity;
1516
* 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
1720
*/
1821
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
1922
List<List<int[]>> graph = new ArrayList();
@@ -31,21 +34,21 @@ public int findTheCity(int n, int[][] edges, int distanceThreshold) {
3134
for (int i = 0; i < n; i++) {
3235
dijkstraAlgo(graph, i, shortestPaths[i]);
3336
}
34-
return findCity(shortestPaths, distanceThreshold);
37+
return findCityWithFewestReachableCities(shortestPaths, distanceThreshold);
3538
}
3639

37-
private int findCity(int[][] shortestPaths, int distanceThreshold) {
40+
private int findCityWithFewestReachableCities(int[][] shortestPaths, int distanceThreshold) {
3841
int ans = 0;
39-
int fewestConnected = shortestPaths.length;
42+
int fewestReachable = shortestPaths.length;
4043
for (int i = 0; i < shortestPaths.length; i++) {
4144
int reachable = 0;
4245
for (int j = 0; j < shortestPaths[0].length; j++) {
4346
if (i != j && shortestPaths[i][j] <= distanceThreshold) {
4447
reachable++;
4548
}
4649
}
47-
if (reachable <= fewestConnected) {
48-
fewestConnected = reachable;
50+
if (reachable <= fewestReachable) {
51+
fewestReachable = reachable;
4952
ans = i;
5053
}
5154
}

0 commit comments

Comments
 (0)