@@ -78,5 +78,58 @@ private int[][] constructGraph(int n, int[][] flights) {
7878 return res ;
7979 }
8080
81+
82+ /**
83+ * https://leetcode.com/problems/cheapest-flights-within-k-stops/solution/
84+ */
85+ public int findCheapestPrice2 (int n , int [][] flights , int src , int dst , int K ) {
86+ int [][] dist = new int [2 ][n ];
87+ int INF = Integer .MAX_VALUE / 2 ;
88+ Arrays .fill (dist [0 ], INF );
89+ Arrays .fill (dist [1 ], INF );
90+ dist [0 ][src ] = dist [1 ][src ] = 0 ;
91+
92+ for (int i = 0 ; i <= K ; ++i )
93+ for (int [] edge : flights )
94+ dist [i &1 ][edge [1 ]] = Math .min (dist [i &1 ][edge [1 ]], dist [~i &1 ][edge [0 ]] + edge [2 ]);
95+
96+ return dist [K &1 ][dst ] < INF ? dist [K &1 ][dst ] : -1 ;
97+ }
98+
99+
100+ /**
101+ * https://leetcode.com/problems/cheapest-flights-within-k-stops/solution/
102+ */
103+ public int findCheapestPrice3 (int n , int [][] flights , int src , int dst , int K ) {
104+ int [][] graph = new int [n ][n ];
105+ for (int [] flight : flights )
106+ graph [flight [0 ]][flight [1 ]] = flight [2 ];
107+
108+ Map <Integer , Integer > best = new HashMap ();
109+
110+ Comparator <int []> comp = (a , b ) -> a [0 ] - b [0 ];
111+ PriorityQueue <int []> pq = new PriorityQueue <int []>(comp );
112+ pq .offer (new int []{0 , 0 , src });
113+
114+ while (!pq .isEmpty ()) {
115+ int [] info = pq .poll ();
116+ int cost = info [0 ], k = info [1 ], place = info [2 ];
117+ if (k > K +1 || cost > best .getOrDefault (k * 1000 + place , Integer .MAX_VALUE ))
118+ continue ;
119+ if (place == dst )
120+ return cost ;
121+
122+ for (int nei = 0 ; nei < n ; ++nei ) if (graph [place ][nei ] > 0 ) {
123+ int newcost = cost + graph [place ][nei ];
124+ if (newcost < best .getOrDefault ((k +1 ) * 1000 + nei , Integer .MAX_VALUE )) {
125+ pq .offer (new int []{newcost , k +1 , nei });
126+ best .put ((k +1 ) * 1000 + nei , newcost );
127+ }
128+ }
129+ }
130+
131+ return -1 ;
132+ }
133+
81134}
82135
0 commit comments