LeetCode/cs/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cs

70 lines
1.9 KiB
C#
Raw Normal View History

public class Solution {
private readonly int UNREACHABLE = 1_000_000_007;
private int[,] MakeDistances(int n, int[][] edges) {
var distances = new int[n, n];
// Everything's unreachable at the beginning, except for self-loops
for (var i = 0; i < n; ++i) {
for (var j = 0; j < n; ++j) {
distances[i, j] = UNREACHABLE;
}
distances[i, i] = 0;
}
// Process the edges
foreach (int[] edge in edges) {
var (u, v, weight) = (edge[0], edge[1], edge[2]);
distances[u, v] = weight;
distances[v, u] = weight;
}
return distances;
}
private void FloydWarshall(int n, int[,] distances) {
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
distances[i, j] = Math.Min(
distances[i, j],
distances[i, k] + distances[k, j]
);
}
}
}
}
private int FindWithFewestReachable(int n, int[,] distances, int threshold) {
int foundCity = -1;
int foundFewest = n;
for (int i = 0; i < n; ++i) {
int reachable = 0;
for (int j = 0; j < n; ++j) {
if (i == j) {
continue;
}
if (distances[i, j] <= threshold) {
++reachable;
}
}
if (reachable <= foundFewest) {
(foundCity, foundFewest) = (i, reachable);
}
}
return foundCity;
}
public int FindTheCity(int n, int[][] edges, int distanceThreshold) {
var distances = MakeDistances(n, edges);
FloydWarshall(n, distances);
return FindWithFewestReachable(n, distances, distanceThreshold);
}
}