class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# 构建dist矩阵
dist = [[float('inf')] * n for _ in range(n)]
for i, j, w in edges:
dist[i][j] = w
dist[j][i] = w
for i in range(n):
dist[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
# 过滤
res = 0
minCnt = float('inf')
for i in range(n):
cnt = 0
for d in dist[i]:
if d <= distanceThreshold:
cnt += 1
if cnt <= minCnt:
minCnt = cnt
res = i
return res
复杂度分析
时间复杂度:$O(N^3)$
空间复杂度:$O(N^2)$
关键点解析
Floyd-Warshall 算法
你可以将本文给的 Floyd-Warshall 算法当成一种解题模板使用
image.png
大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。 大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。