我使用元组集构建图形的以下代码将返回-1(解决方案存在但返回错误-1):
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
# NOTE: Here I use a set
g = collections.defaultdict(set)
for s, d, cost in flights:
g[s].add((cost, d))
q, distance = [(0, 0, src)], {}
heapq.heapify(q)
while q:
cost, stop, city = heapq.heappop(q)
if stop>K+1 or cost>distance.get((stop, city), float('inf')): continue
if city == dst:
return cost
for nbr, c in g.get(city, ()):
if c+cost < distance.get((stop+1, nbr), float('inf')):
distance[(stop+1, nbr)] = c+cost
heapq.heappush(q, (c+cost, stop+1, nbr))
return -1
但是,如果我将图形数据结构更改为 dict 的 dict,则代码可以工作。我已经彻底检查了差异,但仍然找不到答案。是什么导致了这些差异?
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
# NOTE: Here I use a dict
g = collections.defaultdict(dict)
for s, d, cost in flights:
g[s][d]=cost
q, distance = [(0, 0, src)], {}
heapq.heapify(q)
while q:
cost, stop, city = heapq.heappop(q)
if stop>K+1 or cost>distance.get((stop, city), float('inf')): continue
if city == dst:
return cost
for nbr, c in g[city].items():
if c+cost < distance.get((stop+1, nbr), float('inf')):
distance[(stop+1, nbr)] = c+cost
heapq.heappush(q, (c+cost, stop+1, nbr))
return -1