LeetCode 787. Cheapest Flights Within K Stops?

There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.

Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {}

idea:
this questions is easy to understand, so what we need to do:
find the cheapest price from node src too node dst with maximum k stops.
if we can’t find a path from src to dst, or we can’t find the path within k stops. then we return -1.
if any other situations, then we return this minimum weight sum.

so first thing first, we need to construct this directed graph.
and then we traverse this graph and trying to find a way between this given src and dst. so it’s like the modify of shortest path problem, but with given maximum number of stops.
we can choose adj matrix or hashmap, but it’s better for us to choose adj matrix because we are having a weighted graph.
looks like this problem can be solved in so many ways, like regular BFS or DFS or Bellman-ford, or dijkstra.

this problem seems bit of hard, i will deal with it later.

posted @ 2020-12-03 10:23  EvanMeetTheWorld  阅读(28)  评论(0)    收藏  举报