首页 > 其他分享 >Leetcode 1334 Find the City With the Smallest Number of Neighbors at a Threshold Distance

Leetcode 1334 Find the City With the Smallest Number of Neighbors at a Threshold Distance

时间:2024-07-26 15:26:02浏览次数:17  
标签:Neighbors City dist city float Distance inf cities

Problem: Find the City With the Smallest Number of Neighbors at a Threshold Distance

The knowledge points outside of my skill tree

Explanation of Code and Concepts

  1. What is float('inf')?

    • float('inf') in Python represents positive infinity. It is used to initialize distances to a very large number (effectively infinity) so that they can be replaced by any shorter actual distance found during the algorithm’s execution. This is particularly useful in graph algorithms like Floyd-Warshall where you need a way to represent the concept of “no direct path” between nodes.
  2. Matrix Initialization: dist = [[float('inf')] * n for _ in range(n)]

    • This line of code initializes a 2D list (matrix) dist of size n x n where each element is set to float('inf'). Here’s a breakdown of its components:
      • for _ in range(n): This is a list comprehension that iterates n times. The variable _ is conventionally used when the actual value of the variable is not needed.
      • * n: This creates a list containing n elements, all initialized to float('inf'). When you write [float('inf')] * n, it means create a list with n elements, each of which is float('inf').
      • [[float('inf')] * n for _ in range(n)]: The list comprehension iterates n times, creating n lists, each containing n elements of float('inf'). This results in an n x n matrix where all entries are initially set to float('inf').

Description

There are n cities numbered from 0 to n-1. Given an array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given an integer distanceThreshold, return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold. If there are multiple such cities, return the city with the greatest number.

The distance of a path connecting cities i and j is equal to the sum of the edges’ weights along that path.

Examples

Example 1

Input
n = 4
edges = [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]]
distanceThreshold = 4
Output
3
Explanation

The neighboring cities at a distanceThreshold of 4 for each city are:

  • City 0 -> [City 1, City 2]
  • City 1 -> [City 0, City 2, City 3]
  • City 2 -> [City 0, City 1, City 3]
  • City 3 -> [City 1, City 2]

Cities 0 and 3 have 2 neighboring cities at a distanceThreshold of 4, but we return city 3 since it has the greatest number.

Example 2

Input
n = 5
edges = [[0, 1, 2], [0, 4, 8], [1, 2, 3], [1, 4, 2], [2, 3, 1], [3, 4, 1]]
distanceThreshold = 2
Output
0
Explanation

The neighboring cities at a distanceThreshold of 2 for each city are:

  • City 0 -> [City 1]
  • City 1 -> [City 0, City 4]
  • City 2 -> [City 3, City 4]
  • City 3 -> [City 2, City 4]
  • City 4 -> [City 1, City 2, City 3]

City 0 has 1 neighboring city at a distanceThreshold of 2.

Constraints

  • 2 <= n <= 100
  • 1 <= edges.length <= n * (n - 1) / 2
  • edges[i].length == 3
  • 0 <= fromi < toi < n
  • 1 <= weighti, distanceThreshold <= 10^4
  • All pairs (fromi, toi) are distinct.

Solution

Approach

  1. Initialize the Distance Matrix:

    • Create an n x n matrix dist where dist[i][j] represents the shortest distance from city i to city j.
    • Initialize dist[i][i] to 0 for all cities.
    • Initialize dist[i][j] to infinity for all pairs of cities i and j that do not have a direct edge.
    • Set dist[i][j] to the weight of the edge between cities i and j for all given edges.
  2. Run the Floyd-Warshall Algorithm:

    • For each intermediate city k, and for each pair of cities i and j, update dist[i][j] to be the minimum of its current value and the sum of the distances from i to k and from k to j.
  3. Count Reachable Cities:

    • For each city, count how many other cities can be reached with a distance less than or equal to the distanceThreshold.
  4. Find the Desired City:

    • Find the city with the smallest number of reachable cities.
    • In case of a tie, select the city with the greatest numerical value.

Python Code

class Solution(object):
    def findTheCity(self, n, edges, distanceThreshold):
        """
        :type n: int
        :type edges: List[List[int]]
        :type distanceThreshold: int
        :rtype: int
        """
        # Initialize the distance matrix with infinity
        dist = [[float('inf')] * n for _ in range(n)]
        
        # Distance to itself is 0
        for i in range(n):
            dist[i][i] = 0
        
        # Set initial distances based on the edges
        for u, v, w in edges:
            dist[u][v] = w
            dist[v][u] = w
        
        # Floyd-Warshall algorithm to find shortest paths
        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])
        
        # Find the number of reachable cities for each city
        min_count = float('inf')
        result_city = -1
        
        for i in range(n):
            count = sum(1 for j in range(n) if dist[i][j] <= distanceThreshold)
            # If count is the same, choose the city with the larger number
            if count < min_count or (count == min_count and i > result_city):
                min_count = count
                result_city = i
        
        return result_city

Explanation

  1. Distance Initialization:

    • Initialize the distance matrix with float('inf') to represent no direct path between cities, except for the diagonal (distance to itself), which is set to 0.
    • Update the initial distances based on the provided edges.
  2. Floyd-Warshall Algorithm:

    • Iteratively update the shortest paths between all pairs of cities by considering each city as an intermediate node.
  3. Counting Reachable Cities:

    • Count the number of cities that are reachable from each city within the distanceThreshold.
  4. Selecting the Optimal City:

    • Determine the city with the smallest number of reachable cities. In case of a tie, select the city with the larger numerical value.

标签:Neighbors,City,dist,city,float,Distance,inf,cities
From: https://blog.csdn.net/weixin_39280437/article/details/140714917

相关文章

  • 【古瑞瓦特光伏逆变器】防水帝国的绿色创新之路,太city了!
    【古瑞瓦特光伏逆变器】防水帝国的绿色创新之路,太city了!东方雨虹,这艘在防水领域乘风破浪的巨轮,自北京奥运防水项目起航,至中国基建大潮时期逆流而上,其凭借其敏锐的市场洞察和卓越的技术革新,成就了市值千亿的防水帝国。在低碳发展的道路上,东方雨虹不仅在......
  • 音视频入门基础:PCM专题(3)——使用Audacity工具分析PCM音频文件
     =================================================================音视频入门基础:PCM专题系列文章:音视频入门基础:PCM专题(1)——使用FFmpeg命令生成PCM音频文件并播放音视频入门基础:PCM专题(2)——使用Qt播放PCM音频文件音视频入门基础:PCM专题(3)——使用Audacity工具分析PC......
  • 易优CMS模板标签citysite城市站点输出最顶级城市站点,不包括子孙站点,可用于网站简单的
    [基础用法]标签:citysitename值:web_citysite_open描述:易优多城市站点常用标记,可以循环嵌套标签。通常用于多城市站点以获取站点列表信息,方便实现站群与分站的网站。注意事项:1、专业版授权才支持,点击查看如何开启多城市站点2......
  • CF521E Cycling City 题解
    Description给定一张\(n\)个点\(m\)条边的无向简单图。问图中能否找到两个点,满足这两个点之间有至少三条完全不相交的简单路径。\(n,m\le2\times10^5\),图不保证连通。Solution容易发现有解地充要条件是存在两个环有边交,考虑在dfs树上做这件事。注意到非树边一定......
  • D. Sasha and a Walk in the City
    原题链接题意树中任意一条路径上黑色点的数量不超过两个,请问存在多少种树分析先随便找一个节点作为根节点,然后分类讨论假如根到叶子节点的路径上有两个黑色节点,则不能再添加其他点了如果根到叶子节点的路径上有一个黑色节点,则可以还可以在不在这条路径上的地方放黑色节点在......
  • 题解:AT_abc359_c [ABC359C] Tile Distance 2
    背景去中考了,比赛没打,来补一下题。分析这道题让我想起了这道题(连题目名称都是连着的),不过显然要简单一些。这道题显然要推一些式子。我们发现,和上面提到的那道题目一样,沿着对角线走台阶,纵坐标走到以后再走横坐标显然是最优策略。这时候的答案就是横纵坐标差的和的一半(这就不用......
  • 高德解析城市的分析,根据高德的经纬度获取城市cityCode
    高德解析城市的分析,根据高德的经纬度获取城市cityCode高德解析城市的分析,根据高德的经纬度获取城市cityCodehttp://restapi.amap.com/v3/geocode/regeo?output=json&location=110.517039,18.817948&key=替换成自己的高德KEY&extensions=base1.高德返回城市(正常情况)江苏省南......
  • WAIC 2024,好city啊!
    7月4日,“以共商促共享•以善治促善智”为主题的2024世界人工智能大会暨人工智能全球治理高/级别会议(简称“WAIC2024”)在上海举办。天翼云携智算创新成果精彩亮相世博展览馆,全方位展现在人工智能领域的深厚实力。 智算领航,引领科技新方向AI时代,“云智一体”已成为行业共识,在“......
  • F. Minimum Maximum Distance
    原题链接题解1.假设有一个以标记点\(c\)为根的子树,且子树内没有其他标记点,易得该子树内所有点的\(f\leqf(c)\),所以我们可以把该子树内的非标记点全部删掉2.完成步骤1之后,图就变成了所有叶子节点均为标记点的树3.题目等价于求该树内,最小的点到边界的最大值,也就是求树的直径......
  • D. Distance in Tree
    原题链接题解固定一个点作为树的根,易得任意一条链,都可以以某个点作为最高点,且链的两端到最高点之和为\(k\)那么不难想到遍历每个点作为最高点那么接下来就变成了在子树里选两个端点,使得到该点的距离之和为\(k\)这种无序点对统计,我们可以顺序遍历,然后对于每一个遍历到的点,计......