我正在尝试解决LeetCode问题#787,"Cheapest Flights Within K Stops"。
"有n个城市通过一些航班相连接。给定一个数组flights,其中flights[i] = [fromi, toi, pricei]表示从城市fromi到城市toi有一条价格为pricei的航班。还给定三个整数src、dst和k,返回从src到dst的最便宜价格,最多经过k个中转站。如果没有这样的路线,则返回-1。"
然而,我在特定的测试用例中遇到了问题:
flights = [[0,1,5],[1,2,5],[0,3,2],[3,1,2],[1,4,1],[4,2,1]],
n = 5,
src = 0,
dst = 2,
k = 2
预期答案是7,但我的代码返回9。我花了过去的2个小时调试代码,但似乎找不到问题所在。如果有人能指出代码有什么问题,我将非常感激。
代码:
class minHeap {
constructor() {
this.nodes = []
}
enqueue(node, priority, stopsCount) {
if(this.isEmpty()) {
this.nodes.push([node, priority, stopsCount])
} else {
let added = false;
for(let i = 0; i < this.nodes.length; i++) {
if(this.nodes[i][1] > priority) {
this.nodes.splice(i, 0, [node, priority, stopsCount])
added = true
break;
}
}
if(!added) {
this.nodes.push([node, priority, stopsCount])
}
}
}
dequeue() {
return this.nodes.shift()
}
isEmpty() {
return this.nodes.length === 0
}
}
var findCheapestPrice = function(n, flights, src, dst, k) {
const graph = {}
const prices = {}
for(let i = 0; i < n; i++) {
graph[i] = []
if (i == src) {
prices[i] = 0
} else {
prices[i] = Infinity
}
}
for(let [ from, to, price ] of flights) {
graph[from].push([ to, price ])
}
const heap = new minHeap()
heap.enqueue(src, 0, 0)
while (!heap.isEmpty()) {
const [ airport, price, stopsCount ] = heap.dequeue()
for (let neighbor of graph[airport]) {
const [ neighborAirport, neighborPrice ] = neighbor
const priceToNeighbor = neighborPrice + price
if (prices[neighborAirport] > priceToNeighbor && stopsCount <= k) {
prices[neighborAirport] = priceToNeighbor
heap.enqueue(neighborAirport, priceToNeighbor, stopsCount+1)
}
}
}
return prices[dst] == Infinity ? -1 : prices[dst]
};
k=3
(0 -> 1 -> 4 -> 2 (5+1+1 = 7)
),除非我漏掉了什么。你确定这不是一个错误的测试用例吗?另外,对于k=2
,我不知道你的代码是如何得出9的,因为我只能看到一个解决方案 (0 -> 1 -> 2 = 10
),另一条路径0 -> 3 -> 死胡同
是行不通的。 - Luke Vo