Skip to content

Commit 8e4a60c

Browse files
solves #787: cheapest flights within k stops
1 parent 040badf commit 8e4a60c

File tree

3 files changed

+83
-46
lines changed

3 files changed

+83
-46
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,7 @@
416416
| 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix) | [![Java](assets/java.png)](src/ToeplitzMatrix.java) [![Python](assets/python.png)](python/toeplitz_matrix.py) | |
417417
| 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones) | [![Java](assets/java.png)](src/JewelsAndStones.java) [![Python](assets/python.png)](python/jewels_and_stones.py) | |
418418
| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes) | [![Java](assets/java.png)](src/MinimumAbsoluteDifferenceInBST.java) [![Python](assets/python.png)](python/minimum_distance_between_bst_nodes.py) | |
419+
| 787 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops) | [![Java](assets/java.png)](src/CheapestFlightsWithinKStops.java) | |
419420
| 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits) | | |
420421
| 796 | [Rotate String](https://leetcode.com/problems/rotate-string) | [![Java](assets/java.png)](src/RotateString.java) | |
421422
| 797 | [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target) | [![Java](assets/java.png)](src/AllPathsFromSourceToTarget.java) | |

src/CheapestFlightsWithinKStops.java

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// https://leetcode.com/problems/cheapest-flights-within-k-stops
2+
// T: O((N + E) * K)
3+
// S: O(N)
4+
5+
import java.util.Arrays;
6+
7+
public class CheapestFlightsWithinKStops {
8+
9+
public static int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
10+
final int[] distances = bellmanFord(flights, n, k, src);
11+
return distances[dst] == Integer.MAX_VALUE ? -1 : distances[dst];
12+
}
13+
14+
// T: O(N * K + E * K) = T: O((N + E) * K) S: O(N)
15+
private static int[] bellmanFord(int[][] edges, int n, int k, int source) {
16+
int[] distances = initializeDistances(n);
17+
distances[source] = 0;
18+
for (int i = 0 ; i < k + 1 ; i++) {
19+
final int[] temp = cloneArray(distances);
20+
for (int[] edge : edges) {
21+
final int from = edge[0], to = edge[1], weight = edge[2];
22+
if (distances[from] != Integer.MAX_VALUE) {
23+
temp[to] = Math.min(temp[to], distances[from] + weight);
24+
}
25+
}
26+
distances = temp;
27+
}
28+
return distances;
29+
}
30+
31+
// T: O(N), S: O(N)
32+
private static int[] initializeDistances(int n) {
33+
final int[] distances = new int[n];
34+
Arrays.fill(distances, Integer.MAX_VALUE);
35+
return distances;
36+
}
37+
38+
// T: O(N), S: O(N)
39+
private static int[] cloneArray(int[] array) {
40+
final int[] result = new int[array.length];
41+
System.arraycopy(array, 0, result, 0, array.length);
42+
return result;
43+
}
44+
}

src/HelloWorld.java

+38-46
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,58 @@
1-
// T: O(V + EllogV)
2-
// S: O(E + V)
3-
4-
import java.util.Comparator;
5-
import java.util.HashMap;
6-
import java.util.HashSet;
7-
import java.util.Map;
8-
import java.util.PriorityQueue;
9-
import java.util.Queue;
10-
import java.util.Set;
11-
1+
import java.util.*;
122

133
public class HelloWorld {
14-
private static final record Pair(int vertex, int distance) {}
4+
private record Edge(int vertex, int time) {}
155

166
public int networkDelayTime(int[][] times, int n, int k) {
177
final Map<Integer, Map<Integer, Integer>> graph = createGraph(times);
18-
final Map<Integer, Integer> distances = new HashMap<>();
19-
final Queue<Pair> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.distance));
8+
final Map<Integer, Integer> delayTimes = dijkstra(graph, k);
9+
if (delayTimes.size() != n) {
10+
return -1;
11+
}
12+
return delayTimes.values().stream().max(Integer::compare).get();
13+
}
2014

21-
minHeap.add(new Pair(k, 0));
15+
// T: O(E), S: O(E)
16+
private static Map<Integer, Map<Integer, Integer>> createGraph(int[][] edges) {
17+
final Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
18+
for (int[] edge : edges) {
19+
final int from = edge[0], to = edge[1], weight = edge[2];
20+
final Map<Integer, Integer> neighbours = graph.getOrDefault(from, new HashMap<>());
21+
neighbours.put(to, weight);
22+
graph.putIfAbsent(from, neighbours);
23+
}
24+
return graph;
25+
}
2226

23-
while (!minHeap.isEmpty()) {
24-
final Pair pair = minHeap.poll();
25-
final int vertex = pair.vertex, distanceToVertex = pair.distance;
26-
final int currentVertexTime = distances.getOrDefault(vertex, Integer.MAX_VALUE);
27+
// T: O(V + E logV)
28+
private static Map<Integer, Integer> dijkstra(Map<Integer, Map<Integer, Integer>> graph, int start) {
29+
final Map<Integer, Integer> distances = new HashMap<>();
30+
final Queue<Edge> queue = new PriorityQueue<>(Comparator.comparingInt(a -> a.time));
31+
queue.add(new Edge(start, 0));
2732

28-
if (currentVertexTime < distanceToVertex) {
33+
while (!queue.isEmpty()) {
34+
final Edge edge = queue.poll();
35+
if (edge.time >= distances.getOrDefault(edge.vertex, Integer.MAX_VALUE)) {
2936
continue;
3037
}
3138

32-
distances.put(vertex, distanceToVertex);
33-
34-
for (Map.Entry<Integer, Integer> entry : graph.getOrDefault(pair.vertex, new HashMap<>()).entrySet()) {
35-
final int neighbour = entry.getKey(), distance = entry.getValue();
36-
final int currentMinDistance = distances.getOrDefault(neighbour, Integer.MAX_VALUE);
37-
final int minDistance = Math.min(currentMinDistance, distances.get(pair.vertex) + distance);
39+
distances.put(edge.vertex, edge.time);
3840

39-
if (minDistance < currentMinDistance) {
40-
distances.put(neighbour, minDistance);
41-
minHeap.add(new Pair(neighbour, minDistance));
42-
}
41+
for (Map.Entry<Integer, Integer> entry : graph.getOrDefault(edge.vertex, new HashMap<>()).entrySet()) {
42+
final int neighbour = entry.getKey(), time = entry.getValue();
43+
queue.add(new Edge(neighbour, edge.time + time));
4344
}
4445
}
4546

46-
return minTimeRequired(distances, n);
47+
return distances;
4748
}
4849

49-
private static Map<Integer, Map<Integer, Integer>> createGraph(int[][] edges) {
50-
final Map<Integer, Map<Integer, Integer>> result = new HashMap<>();
51-
for (int[] edge : edges) {
52-
final int from = edge[0], to = edge[1], weight = edge[2];
53-
final Map<Integer, Integer> weights = result.getOrDefault(from, new HashMap<>());
54-
weights.put(to, weight);
55-
result.putIfAbsent(from, weights);
56-
}
57-
return result;
58-
}
50+
public static void main(String[] args) {
51+
int[] b = new int[] {1, 2, 3};
52+
int[] a = b;
53+
System.out.println(Arrays.toString(a));
54+
b = new int[] {5, 6, 7};
55+
System.out.println(Arrays.toString(a));
5956

60-
private static int minTimeRequired(Map<Integer, Integer> distances, int n) {
61-
if (distances.size() != n) {
62-
return -1;
63-
}
64-
return distances.values().stream().max(Integer::compareTo).get();
6557
}
6658
}

0 commit comments

Comments
 (0)