2019.7.18 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
这题是今年华为实习开发岗的笔试题,原题题干改成了蜜蜂采蜜的最短路径。
做法主要有两种:
1.最小堆+BFS
先将所有边的关系保存在二维数组edge中,将起始点加入最小堆,每次循环将最小堆中的最小值(当前花费最小的站)出堆作为当前结点curCity(如果curCity的步数超过K则重新出堆),遍历计算curCity到所有结点的花费和步数,如果花费和步数比原先更低,那么更新记录并把新结点入堆。遍历到目的结点时停止。
为了优化代码,可以先用HashMap创建一个图,存储边的关系。创建最小堆保存路径结果(花费,当前结点,当前剩余步数),显然,先将new int[] {0, src, k + 1}入堆。接着不断遍历相邻的每一个剩余步数大于0的结点,并不断将更新了花费和步长的结点入堆即可。
2.动态规划
dp[i][k]表示经过k步到达站i的最短距离,将dp[src]设置为0,其余为Integer.MAX_VALUE。从K=1开始,每次对所有飞机更新一步,经过k步到达dst的最短距离 = 经过k-1步到达src的距离 + 两者距离,若有更短的结果则进行更新。最后返回dp[dst][K+1]即可。
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.
有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1。
示例 1:
输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
输出: 200
解释:
从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200。
import java.util.*;
/**
* 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.
* 有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
* 现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1。
*/
public class CheapestFlightsWithinKStops {
public static void main(String[] args) {
int[][] edges = {
{
0, 1, 100}, {
1, 2, 100}, {
0, 2, 500}};
System.out.println(findCheapestPrice(3, edges, 0, 2, 1));
System.out.println(findCheapestPrice1(3, edges, 0, 2, 1));
System.out.println(findCheapestPrice2(3, edges, 0, 2, 1));
}
//基于Dijsktra算法(堆 + BFS)
//每次从优先队列中poll出一个当前最小步数的站, 如果该站为dst则直接返回
//城市结点类
static class Vertex implements Comparable<Vertex> {
int id;
int costFromSrc; //截至当前的路长
int idxFromSrc; //截至当前的结点数
Vertex(int id, int costFromSrc, i