Scribbling

LeetCode: 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance 본문

Computer Science/Coding Test

LeetCode: 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance

focalpoint 2021. 8. 10. 21:57
class Solution:
    def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
        INF = int(1e9)
        
        distance = [[INF] * (n) for _ in range(n)]
        for i in range(n):
            distance[i][i] = 0
        
        for edge in edges:
            u = edge[0]
            v = edge[1]
            w = edge[2]
            distance[u][v] = w
            distance[v][u] = w
        
        for k in range(n):
            for a in range(n):
                for b in range(n):
                    distance[a][b] = min(distance[a][b], distance[a][k] + distance[k][b])
        
        num_reachable_list = []
        for i in range(n):
            num_reachable = 0
            for j in range(n):
                if distance[i][j] <= distanceThreshold:
                    num_reachable += 1
            num_reachable_list.append(num_reachable)
        
        num_min = min(num_reachable_list)
        for idx in range(n-1, -1, -1):
            if num_reachable_list[idx] == num_min:
                return idx