Description:
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.
Now given all the cities and fights, 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.
Note:
- The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
- The size of flights will be in range [0, n * (n - 1) / 2].
- The format of each flight will be (src, dst, price).
- The price of each flight will be in the range [1, 10000].
- k is in the range of [0, n - 1].
- There will not be any duplicated flights or self cycles.
问题描述:
n个城市有m个航班连接。每个航班由u到v,机票费为w。
给定n个城市和所有航班。起始城市为src,目的城市为dst.你需要返回由src到dst最多k站花费的最少的钱。如果没有这样一条路线,返回-1.
问题分析:
两种解法,优先级队列或者Dijkstra
解法1(使用优先级队列):
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
for(int[] f : flights){
graph.put(f[0], graph.getOrDefault(f[0], new HashMap<>()));
graph.get(f[0]).put(f[1], f[2]);
}
Queue<int[]> pq = new PriorityQueue<>((a,b) -> (Integer.compare(a[0], b[0])));
pq.add(new int[]{0, src, k + 1});
while(!pq.isEmpty()) {
int[] top = pq.remove();
int price = top[0];
int city = top[1];
int stops = top[2];
if(city == dst) return price;
if(stops > 0) {
Map<Integer, Integer> adj = graph.get(city);
if(adj != null){
for(int a : adj.keySet()){
pq.add(new int[]{price + adj.get(a), a, stops - 1});
}
}
}
}
return -1;
}
}
解法2(Dijkstra):
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] adj = new int[n][n];
for(int[] f : flights) adj[f[0]][f[1]] = f[2];
Queue<Integer> q = new LinkedList();
q.add(src);
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
int stp = K + 1;
while (!q.isEmpty() && stp > 0)
{
int size = q.size();
int[] tmp = Arrays.copyOf(dist, dist.length);
for (int t = 0; t < size; t++)
{
int cur = q.poll();
for (int i = 0; i < n; i++)
{
if (adj[cur][i] > 0 && dist[cur] + adj[cur][i] < tmp[i])
{
tmp[i] = dist[cur] + adj[cur][i];
q.add(i);
}
}
}
stp--;
dist = tmp;
}
return dist[dst] != Integer.MAX_VALUE? dist[dst] : -1;
}
}