cs: add «1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
31c882dfcd
commit
38a46aeb26
1 changed files with 69 additions and 0 deletions
|
@ -0,0 +1,69 @@
|
|||
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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue