Skip to content

Commit

Permalink
Cheapest Flights Within K Stops
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 1, 2023
1 parent 83266bb commit 9346a66
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ add_task(can-place-flowers)
add_task(candy)
add_task(capacity-to-ship-packages-within-d-days)
add_task(champagne-tower)
add_task(cheapest-flights-within-k-stops)
add_task(check-completeness-of-a-binary-tree)
add_task(check-if-array-is-sorted-and-rotated)
add_task(check-if-it-is-a-straight-line)
Expand Down
1 change: 1 addition & 0 deletions solutions/cheapest-flights-within-k-stops/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_cheapest_flights_within_k_stops test.cpp)
41 changes: 41 additions & 0 deletions solutions/cheapest-flights-within-k-stops/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#pragma once

#include <algorithm>
#include <climits>
#include <queue>
#include <vector>

class Solution {
public:
static int findCheapestPrice(int n,
const std::vector<std::vector<int>> &flights,
int src, int dst, int k) {
std::vector<std::vector<std::pair<int, int>>> graph(n);
for (const auto &edge : flights) {
const auto from = edge[0], to = edge[1], price = edge[2];
graph[from].push_back({to, price});
}

std::vector<int> distances(n, INT_MAX);
distances[src] = 0;

std::queue<std::pair<int, int>> queue;
queue.push({src, 0});

for (int stops = 0; !queue.empty() && stops <= k; ++stops) {
for (int sz = queue.size(); sz; --sz) {
const auto [u, distance] = queue.front();
queue.pop();

for (const auto &[v, w] : graph[u]) {
if (distances[v] > distance + w) {
distances[v] = distance + w;
queue.push({v, distance + w});
}
}
}
}

return distances[dst] == INT_MAX ? -1 : distances[dst];
}
};
27 changes: 27 additions & 0 deletions solutions/cheapest-flights-within-k-stops/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
int n = 4;
std::vector<std::vector<int>> flights{
{0, 1, 100}, {1, 2, 100}, {2, 0, 100}, {1, 3, 600}, {2, 3, 200}};
int src = 0, dst = 3, k = 1;
REQUIRE(700 == Solution::findCheapestPrice(n, flights, src, dst, k));
}
{
int n = 3;
std::vector<std::vector<int>> flights{
{0, 1, 100}, {1, 2, 100}, {0, 2, 500}};
int src = 0, dst = 2, k = 1;
REQUIRE(200 == Solution::findCheapestPrice(n, flights, src, dst, k));
}
{
int n = 3;
std::vector<std::vector<int>> flights{
{0, 1, 100}, {1, 2, 100}, {0, 2, 500}};
int src = 0, dst = 2, k = 0;
REQUIRE(500 == Solution::findCheapestPrice(n, flights, src, dst, k));
}
}

0 comments on commit 9346a66

Please sign in to comment.