|
| 1 | +/** |
| 2 | + * 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance |
| 3 | + * https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n cities numbered from 0 to n-1. Given the array edges where |
| 7 | + * edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities |
| 8 | + * fromi and toi, and given the integer distanceThreshold. |
| 9 | + * |
| 10 | + * Return the city with the smallest number of cities that are reachable through some path and whose |
| 11 | + * distance is at most distanceThreshold, If there are multiple such cities, return the city with |
| 12 | + * the greatest number. |
| 13 | + * |
| 14 | + * Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' |
| 15 | + * weights along that path. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @param {number[][]} edges |
| 21 | + * @param {number} distanceThreshold |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var findTheCity = function(n, edges, distanceThreshold) { |
| 25 | + const distances = Array.from({ length: n }, () => Array(n).fill(Infinity)); |
| 26 | + |
| 27 | + for (let i = 0; i < n; i++) { |
| 28 | + distances[i][i] = 0; |
| 29 | + } |
| 30 | + |
| 31 | + for (const [from, to, weight] of edges) { |
| 32 | + distances[from][to] = weight; |
| 33 | + distances[to][from] = weight; |
| 34 | + } |
| 35 | + |
| 36 | + for (let k = 0; k < n; k++) { |
| 37 | + for (let i = 0; i < n; i++) { |
| 38 | + for (let j = 0; j < n; j++) { |
| 39 | + distances[i][j] = Math.min(distances[i][j], distances[i][k] + distances[k][j]); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + let minNeighbors = n; |
| 45 | + let result = 0; |
| 46 | + |
| 47 | + for (let i = 0; i < n; i++) { |
| 48 | + const neighbors = distances[i].filter(dist => dist <= distanceThreshold).length - 1; |
| 49 | + if (neighbors <= minNeighbors) { |
| 50 | + minNeighbors = neighbors; |
| 51 | + result = i; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return result; |
| 56 | +}; |
0 commit comments