Cheapest Flights Within K Stops

LeetCode Q 787 - Cheapest Flights Within K Stops

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 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.

Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200

Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500

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.

Solution

Solution 1: Dijkstra’s algorithm

Code:

class Edge {
	int to, int weight;
	public Edge (int to, int weight) {
		this.to = to; this.weigth = weight;
	}
}

class Stop {
	int id, count, price;
	public Stop (int id, int count, int price) {
		this.id = id; this.count = count; this.price = price;
	}
}

public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K){
	Map<Integer, List<Edge>> graph = new HashMap<>();
	for (int[] f: flights) {
		graph.putIfAbsent(f[0], new ArrayList<>());
		graph.get(f[0]).add(new Edge (f[1], f[2]));
	}

	Queue<Stop> pq = new PriorityQueue<>((a, b) -> (a.price - b.price));
	pq.offer(new Stop (src, K + 1, 0));

	while (!pq.isEmpty()) {
		Stop stop = pq.poll();
		if (stop.id == dst) return stop.price;
		if (stop.count > 0) {
			List<Edge> list = graph.getOrDefault(curr.id, new ArrayList());
			for (Edge e: edges)
				pq.offer(new Stop(e.to, stop.count - 1, stop.price + e.weight));
		}
	}

	return -1;
}

Solution 2: DP

  1. States: long[k][i] dp represents the minimum price that flight from src to i within k - 1 steps.

  2. State Transfer Function:
    dp[i][flight[1]] = Math.min(dp[i][flight[1]], dp[i - 1][flight[0]] + flight[2]);

Code:

public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
	long[][] dp = new long[K + 2][n];

	for (long[] arr: dp)
		Arrays.fill(arr, Integer.MAX_VALUE);
	dp[0][src] = 0;

	for (int i = 1; i < K + 2; i++) {
		dp[i][src] = 0;
		for (int[] flight: flights) {
			dp[i][flight[1]] = Math.min(dp[i][flight[1]], dp[i - 1][flight[0]] + flight[2]);
		}
	}

	return dp[K + 1][dst] == Integer.MAX_VALUE ? -1 : (int)dp[K + 1][dst];
}

   Reprint policy


《Cheapest Flights Within K Stops》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC