Graph Theory37 sections · 1633 units
Open in Course

LeetCode 1334 Find the City - Implementation

(Using Floyd-Warshall)

Initialize distdist with edge weights, run Floyd-Warshall. For each city ii, count reachable cities within threshold:

min_count := n
result := 0
for i from 0 to n - 1
    count := 0
    for j from 0 to n - 1
        if i != j and dist[i][j] <= threshold then
            count := count + 1
    if count <= min_count then
        min_count := count
        result := i
return result

Return result. The <= in the final comparison ensures ties go to the larger city.

This runs in O(n3)O(n^3) time and uses O(n2)O(n^2) space.