From 38a46aeb2607f976180e179d0fdfbe4b71aac355 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 26 Jul 2024 18:00:46 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1334.=20Find=20the=20City=20W?= =?UTF-8?q?ith=20the=20Smallest=20Number=20of=20Neighbors=20at=20a=20Thres?= =?UTF-8?q?hold=20Distance=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...er-of-neighbors-at-a-threshold-distance.cs | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 cs/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cs diff --git a/cs/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cs b/cs/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cs new file mode 100644 index 0000000..d27a495 --- /dev/null +++ b/cs/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.cs @@ -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); + } +}