Skip to content

Commit 249416e

Browse files
committed
Time: 264 ms (78.18%), Space: 17.7 MB (60.27%) - LeetHub
1 parent b14d51f commit 249416e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
3+
inf = float('inf')
4+
# Step 1: Initialize the distance matrix with inf
5+
dist = [[inf] * n for _ in range(n)]
6+
7+
# Distance from a city to itself is 0
8+
for i in range(n):
9+
dist[i][i] = 0
10+
11+
# Step 2: Fill the initial distances from the edges
12+
for u, v, w in edges:
13+
dist[u][v] = w
14+
dist[v][u] = w
15+
16+
# Step 3: Apply Floyd-Warshall Algorithm to find shortest paths between all pairs of cities
17+
for k in range(n):
18+
for i in range(n):
19+
for j in range(n):
20+
if dist[i][j] > dist[i][k] + dist[k][j]:
21+
dist[i][j] = dist[i][k] + dist[k][j]
22+
23+
# Step 4: Count reachable cities within distance threshold for each city
24+
min_count = inf
25+
result_city = -1
26+
27+
for i in range(n):
28+
count = sum(1 for j in range(n) if dist[i][j] <= distanceThreshold)
29+
30+
# Choose the city with the smallest count, and in case of ties, the city with the greatest index
31+
if count < min_count or (count == min_count and i > result_city):
32+
min_count = count
33+
result_city = i
34+
35+
return result_city

0 commit comments

Comments
 (0)