Skip to content

Commit f81d389

Browse files
committed
leetcode
1 parent 03eae25 commit f81d389

File tree

4 files changed

+339
-0
lines changed

4 files changed

+339
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
/*
2+
3+
4+
-* 787. Cheapest Flights Within K Stops *-
5+
6+
7+
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
8+
9+
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
10+
11+
12+
13+
Example 1:
14+
15+
16+
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
17+
Output: 700
18+
Explanation:
19+
The graph is shown above.
20+
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
21+
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
22+
Example 2:
23+
24+
25+
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
26+
Output: 200
27+
Explanation:
28+
The graph is shown above.
29+
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
30+
Example 3:
31+
32+
33+
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
34+
Output: 500
35+
Explanation:
36+
The graph is shown above.
37+
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
38+
39+
40+
Constraints:
41+
42+
1 <= n <= 100
43+
0 <= flights.length <= (n * (n - 1) / 2)
44+
flights[i].length == 3
45+
0 <= from-i, toi < n
46+
from-i != toi
47+
1 <= price-i <= 104
48+
There will not be any multiple flights between two cities.
49+
0 <= src, dst, k < n
50+
src != dst
51+
52+
53+
*/
54+
55+
import 'dart:collection';
56+
import 'dart:math';
57+
58+
class A {
59+
int findCheapestPrice(
60+
int n, List<List<int>> flights, int src, int dst, int k) {
61+
// Build graph
62+
// node -> [[neighbor,distance]]
63+
HashMap<int, List<List<int>>> graph = HashMap();
64+
for (int i = 0; i < n; i++) graph[i] = [];
65+
66+
for (List<int> flight in flights) {
67+
int u = flight[0];
68+
int v = flight[1];
69+
int w = flight[0];
70+
71+
graph[u]?.add([v, w]);
72+
}
73+
74+
// int[] -> [node, distance, moves] for every index
75+
// (a, b) -> a[1] - b[1]
76+
Queue<List<int>> pq = Queue()..toList().sort((a, b) => a[1] - b[1]);
77+
78+
List<int> distance = List.filled(n, -1);
79+
80+
List<int> maxMovesUpToNode = List.filled(n, double.maxFinite.toInt());
81+
82+
// Initial mark
83+
distance[src] = 0;
84+
pq.add([src, 0, 0]);
85+
86+
// Run Relaxation Algorithm
87+
while (pq.isNotEmpty) {
88+
// poll remove First
89+
List<int> element = pq.removeFirst();
90+
int node = element[0];
91+
int dis = element[1];
92+
int moves = element[2];
93+
94+
if (maxMovesUpToNode[node] < moves) continue;
95+
maxMovesUpToNode[node] = moves;
96+
97+
for (List<int> edge in graph[node] ?? []) {
98+
int neighbor = edge[0], weight = edge[1];
99+
100+
int neighborNewDistance = weight + dis;
101+
if (distance[neighbor] == -1 ||
102+
neighborNewDistance < distance[neighbor]) {
103+
distance[neighbor] = neighborNewDistance;
104+
}
105+
// If we have moves left.
106+
if (k != moves) {
107+
pq.add([neighbor, neighborNewDistance, moves + 1]);
108+
}
109+
}
110+
}
111+
112+
return distance[dst];
113+
}
114+
}
115+
116+
class B {
117+
int findCheapestPrice(
118+
int n, List<List<int>> flights, int src, int dst, int k) {
119+
// dp[i][j]: min cost to reach city j using at most i edges from src
120+
List<List<int>> dp = List.filled(k + 2, 0)
121+
.map((e) => List.filled(n, double.maxFinite.toInt()))
122+
.toList();
123+
124+
// base case
125+
for (int i = 0; i <= k + 1; i++) dp[i][src] = 0;
126+
// iterate each stop
127+
for (int i = 1; i <= k + 1; i++) {
128+
// iterate each flight
129+
for (List<int> f in flights) {
130+
int from = f[0], to = f[1], cost = f[2];
131+
// ensure city `from` is reachable
132+
if (dp[i - 1][from] != double.maxFinite.toInt()) {
133+
// from + cost -> to
134+
dp[i][to] = min(dp[i][to], dp[i - 1][from] + cost);
135+
}
136+
}
137+
}
138+
// if dp[k + 1][dst] == INT_MAX, it means it is unreachable
139+
// else return the cost
140+
return dp[k + 1][dst] == double.maxFinite.toInt() ? -1 : dp[k + 1][dst];
141+
}
142+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package main
2+
3+
import "math"
4+
5+
type Connection struct {
6+
city int
7+
cost int
8+
}
9+
10+
type queue []Connection
11+
12+
func (q *queue) push(c Connection) {
13+
q1 := []Connection{c}
14+
*q = append(*q, q1...)
15+
}
16+
17+
func (q *queue) pop() (bool, Connection) {
18+
19+
if q.isEmpty() {
20+
return false, Connection{}
21+
} else {
22+
elem := (*q)[0]
23+
*q = (*q)[1:]
24+
return true, elem
25+
}
26+
}
27+
28+
func (q queue) isEmpty() bool {
29+
return q.size() <= 0
30+
}
31+
32+
func (q queue) size() int {
33+
return len(q)
34+
}
35+
36+
func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int {
37+
38+
minCost := math.MaxInt64
39+
40+
fQueue := new(queue)
41+
fQueue.push(Connection{src, 0})
42+
43+
maxStops := k + 1
44+
45+
costOfFlights := make([][]int, n)
46+
for i := range costOfFlights {
47+
costOfFlights[i] = make([]int, n)
48+
}
49+
50+
flightsMap := make(map[int][]int)
51+
for _, v := range flights {
52+
if _, ok := flightsMap[v[0]]; ok {
53+
flightsMap[v[0]] = append(flightsMap[v[0]], v[1])
54+
} else {
55+
flightsMap[v[0]] = []int{v[1]}
56+
}
57+
58+
costOfFlights[v[0]][v[1]] = v[2]
59+
}
60+
61+
cityPathCost := make([]int, n) // path cost from source
62+
for i := range cityPathCost {
63+
cityPathCost[i] = math.MaxInt64
64+
}
65+
66+
cityPathCost[src] = 0
67+
68+
for !fQueue.isEmpty() && maxStops >= 0 {
69+
70+
size := fQueue.size()
71+
maxStops--
72+
73+
for size > 0 {
74+
_, c := fQueue.pop()
75+
size--
76+
77+
if c.city == dst {
78+
if minCost > c.cost {
79+
minCost = c.cost
80+
}
81+
continue
82+
}
83+
84+
for _, v := range flightsMap[c.city] {
85+
86+
newCost := c.cost + costOfFlights[c.city][v]
87+
88+
if cityPathCost[v] > newCost {
89+
fQueue.push(Connection{v, newCost})
90+
cityPathCost[v] = newCost
91+
}
92+
}
93+
}
94+
}
95+
96+
if minCost == math.MaxInt64 {
97+
minCost = -1
98+
}
99+
100+
return minCost
101+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# 🔥 2 Approaches 🔥 || Simple Fast and Easy || with Explanation
2+
3+
```dart
4+
5+
class Solution {
6+
int findCheapestPrice(
7+
int n, List<List<int>> flights, int src, int dst, int k) {
8+
// dp[i][j]: min cost to reach city j using at most i edges from src
9+
List<List<int>> dp =
10+
List.filled(k + 2, 0).map((e) => List.filled(n, double.maxFinite.toInt())).toList();
11+
12+
13+
14+
// base case
15+
for (int i = 0; i <= k + 1; i++) dp[i][src] = 0;
16+
// iterate each stop
17+
for (int i = 1; i <= k + 1; i++) {
18+
// iterate each flight
19+
for (List<int> f in flights) {
20+
int from = f[0], to = f[1], cost = f[2];
21+
// ensure city `from` is reachable
22+
if (dp[i - 1][from] != double.maxFinite.toInt()) {
23+
// from + cost -> to
24+
dp[i][to] = min(dp[i][to], dp[i - 1][from] + cost);
25+
}
26+
}
27+
}
28+
// if dp[k + 1][dst] == double.maxFinite.toInt(), it means it is unreachable
29+
// else return the cost
30+
return dp[k + 1][dst] == double.maxFinite.toInt() ? -1 : dp[k + 1][dst];
31+
}
32+
}
33+
```
34+
35+
## Solution - 2
36+
37+
```dart
38+
import 'dart:collection';
39+
40+
class Solution {
41+
int findCheapestPrice(
42+
int n, List<List<int>> flights, int src, int dst, int k) {
43+
// Build graph
44+
// node -> [[neighbor,distance]]
45+
HashMap<int, List<List<int>>> graph = HashMap();
46+
for (int i = 0; i < n; i++) graph[i] = [];
47+
48+
for (List<int> flight in flights) {
49+
int u = flight[0];
50+
int v = flight[1];
51+
int w = flight[0];
52+
53+
graph[u]?.add([v, w]);
54+
}
55+
56+
// List<int> -> [node, distance, moves] for every index
57+
Queue<List<int>> pq = Queue()..toList().sort((a, b) => a[1] - b[1]);
58+
59+
List<int> distance = List.filled(n, -1);
60+
61+
List<int> maxMovesUpToNode = List.filled(n, double.maxFinite.toInt());
62+
63+
// Initial mark
64+
distance[src] = 0;
65+
pq.add([src, 0, 0]);
66+
67+
// Run Relaxation Algorithm
68+
while (pq.isNotEmpty) {
69+
List<int> element = pq.removeFirst();
70+
int node = element[0];
71+
int dis = element[1];
72+
int moves = element[2];
73+
74+
if (maxMovesUpToNode[node] < moves) continue;
75+
maxMovesUpToNode[node] = moves;
76+
77+
for (List<int> edge in graph[node] ?? []) {
78+
int neighbor = edge[0], weight = edge[1];
79+
80+
int neighborNewDistance = weight + dis;
81+
if (distance[neighbor] == -1 ||
82+
neighborNewDistance < distance[neighbor]) {
83+
distance[neighbor] = neighborNewDistance;
84+
}
85+
// If we have moves left.
86+
if (k != moves) {
87+
pq.add([neighbor, neighborNewDistance, moves + 1]);
88+
}
89+
}
90+
}
91+
92+
return distance[dst];
93+
}
94+
}
95+
```

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ This repo contain leetcode solution using DART and GO programming language. Most
194194
- [**131.** Palindrome Partitioning](PalindromePartitioning/palindrome_partitioning.dart)
195195
- [**909.** Snakes and Ladders](SnakesAndLadders/snakes_and_ladders.dart)
196196
- [**2359.** Find Closest Node to Given Two Nodes](FindClosestNodeToGivenTwoNodes/find_closest_node_to_given_two_nodes.dart)
197+
- [**787.** Cheapest Flights Within K Stops](CheapestFlightsWithinKStops/cheapest_flights_within_k_stops.dart)
197198

198199
## Reach me via
199200

0 commit comments

Comments
 (0)