码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode1334

时间:2020-01-26 19:23:59      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:ber   algo   with   使用   find   一个   sort   jks   https   

 1 from heapq import heappush, heappop
 2 class Solution:
 3     def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
 4         dis = [[float(inf)]*n for _ in range(n)]
 5         nei = collections.defaultdict(list)
 6         for i,j,x in edges:
 7             dis[i][j] = dis[j][i] = x
 8             nei[i].append(j)
 9             nei[j].append(i)
10         for i in range(n):
11             dis[i][i] = 0
12         
13         # Dijkstra
14         visited = set()
15         for i in range(n):
16             pool = [(0,i)]                                          # pool[j] = x:  d(i,j) = x    
17             while pool:
18                 x,j = heappop(pool)                                 # x = d(i,j)
19                 if (i,j) not in visited and x <= distanceThreshold: # early stop, if distance exceeds threshold
20                     visited.add((i,j))
21                     for k in nei[j]:
22                         dis[i][k] = min(dis[i][k], x+dis[j][k])     # dis(i,k) = min(dis(i,k), dis(i,j)+dis(j,k))
23                         heappush(pool, (dis[i][k], k))
24         cities = [[i,0] for i in range(n)]
25         for i in range(n):
26             for d in dis[i]:
27                 if d <= distanceThreshold:
28                     cities[i][1] += 1
29         result = sorted(cities,key=lambda x:[x[1],-x[0]])[0][0]
30         return result

 

算法思路:图,单源最短路径,Dijkstra算法。

计算每一个点到其他可达点的最小路径,再与阈值进行比较。统计每一个城市为起点,满足阈值范围内的可到达的其他城市的数量,再使用双条件排序,得到最终结果。

参考:https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/490614/Python-3-Dijkstra-Algorithm

24-29行,是我自己的代码,比原帖中的写的要容易理解一些。

leetcode1334

标签:ber   algo   with   使用   find   一个   sort   jks   https   

原文地址:https://www.cnblogs.com/asenyang/p/12234539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!