力扣—1334阈值距离内邻居最少的城市

题目描述

有 n 个城市,按从 0 到 n-1 编号。给你一个边数组 edges,其中 edges[i] = [fromi, toi, weighti] 代表 fromi 和 toi 两个城市之间的双向加权边,距离阈值是一个整数 distanceThreshold。

返回能通过某些路径到达其他城市数目最少、且路径距离 最大 为 distanceThreshold 的城市。如果有多个这样的城市,则返回编号最大的城市。

注意,连接城市 i 和 j 的路径的距离等于沿该路径的所有边的权重之和。

 

示例 1:

 

输入:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
输出:3
解释:城市分布图如上。
每个城市阈值距离 distanceThreshold = 4 内的邻居城市分别是:
城市 0 -> [城市 1, 城市 2] 
城市 1 -> [城市 0, 城市 2, 城市 3] 
城市 2 -> [城市 0, 城市 1, 城市 3] 
城市 3 -> [城市 1, 城市 2] 
城市 0 和 3 在阈值距离 4 以内都有 2 个邻居城市,但是我们必须返回城市 3,因为它的编号最大。


示例 2:

 

输入:n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
输出:0
解释:城市分布图如上。 
每个城市阈值距离 distanceThreshold = 2 内的邻居城市分别是:
城市 0 -> [城市 1] 
城市 1 -> [城市 0, 城市 4] 
城市 2 -> [城市 3, 城市 4] 
城市 3 -> [城市 2, 城市 4]
城市 4 -> [城市 1, 城市 2, 城市 3] 
城市 0 在阈值距离 4 以内只有 1 个邻居城市。

解题思路

Djikstra算法

这个算法适合求单源最短路径,即从一个起点到其他点的最短距离,用到本题中也可以做,使用一个for循环求每个点到其他点的路径,再做比较即可。

网上看到两篇Djikstra算法讲得很清楚的博客,特此记录一下:

https://blog.csdn.net/heroacool/article/details/51014824

https://zhuanlan.zhihu.com/p/63395403

本题首先根据边来构造邻接矩阵,然后再使用Djikstra算法

class Solution(object):
    def findTheCity(self, n, edges, distanceThreshold):
        def Djikstra(source, threshold):
            maximum = float('inf')
            neibour_matrix = [[maximum] * n for i in range(n)]
            for i, j, w in edges:
                neibour_matrix[i][i] = 0
                neibour_matrix[j][j] = 0
                neibour_matrix[i][j] = w
                neibour_matrix[j][i] = w
            passed = [source]
            nopass = [x for x in range(n) if x != source]
            dis = neibour_matrix[source]
            while nopass:
                idx = nopass[0]
                for i in nopass:
                    if dis[i] < dis[idx]:
                        idx = i
                nopass.remove(idx)
                passed.append(idx)
                for i in nopass:
                    if dis[idx] + neibour_matrix[idx][i] < dis[i]:
                        dis[i] = dis[idx] + neibour_matrix[idx][i]
            return [i for i in range(len(dis)) if dis[i] <= distanceThreshold and dis[i] != 0]

        num = n + 1
        ret = -1
        node_dict = {}
        for i in range(n):
            x = Djikstra(i, distanceThreshold)
            if len(x) <= num:
                ret = i
                num = len(x)
        return ret

S = Solution()
print(S.findTheCity(4, [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], 4))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值