每日一题 1334. 阈值距离内邻居最少的城市(中等,图最短路径)

在这里插入图片描述
我还以为官方有更好的解法,没想到也是 O(n3) 的 Floyd 算法

class Solution:
    def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
        ans = (inf, -1)
        mp = [[inf] * n for _ in range(n)]

        for fr, to, weight in edges:
            mp[fr][to], mp[to][fr] = weight, weight
        for k in range(n):
            mp[k][k] = 0
            for i in range(n):
                for j in range(n):
                    mp[i][j] = min(mp[i][j], mp[i][k] + mp[k][j])
        for i in range(n):
            cnt = sum(mp[i][j] <= distanceThreshold for j in range(n))
            if cnt <= ans[0]:
                ans = (cnt, i)
        return ans[1]

你可能感兴趣的:(用Python刷力扣,算法,leetcode,python)