Find the City With the Smallest Number of Neighbors at a Threshold Distance
LeetCode 1334 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Floyd–Warshall, then count reachable cities.
ನಾನು Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / Floyd-Warshall ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
You need shortest distances between every pair of cities, which Floyd–Warshall gives by trying every city as an intermediate stop. Then count how many cities each city reaches within the threshold.
Approach
- 1
Initialise dist with edges and zeros on the diagonal.
- 2
For each via: dist[i][j] = min(dist[i][j], dist[i][via] + dist[via][j]).
- 3
Count cities within the threshold for each source.
- 4
Ties go to the larger city number (<=).
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Floyd–WarshallPythonO(n³) time
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
#floyd marshal algo, multi source graph - via
#dist[i][j]=min(dist[i][j],dist[i][via]+dist[via][j])
dist = [[float("inf")]*n for _ in range(n)]
for u,v,w in edges:
dist[u][v]=w
dist[v][u]=w
for i in range(n):
dist[i][i]=0
for via in range(n):
for i in range(n):
for j in range(n):
if dist[i][via]==float("inf") or dist[via][j]==float("inf"):
continue
dist[i][j]=min(dist[i][j],dist[i][via]+dist[via][j])
min_count=n
src_city = None
for src in range(n):
count = 0
for dest in range(n):
if dist[src][dest]<=distanceThreshold:
count+=1
if count<=min_count:
min_count = count
src_city=src
return src_city
Find the City With the Smallest Number of Neighbors at a Threshold Distance — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Find the City With the Smallest Number of Neighbors at a Threshold Distance ಹಿಂದಿನ intuition ಏನು?
You need shortest distances between every pair of cities, which Floyd–Warshall gives by trying every city as an intermediate stop. Then count how many cities each city reaches within the threshold.
Find the City With the Smallest Number of Neighbors at a Threshold Distance (LeetCode 1334) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Initialise dist with edges and zeros on the diagonal. 2. For each via: dist[i][j] = min(dist[i][j], dist[i][via] + dist[via][j]). 3. Count cities within the threshold for each source. 4. Ties go to the larger city number (<=).
Find the City With the Smallest Number of Neighbors at a Threshold Distance ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n³). Space: O(n²). (Accepted approach: Floyd–Warshall.)
Find the City With the Smallest Number of Neighbors at a Threshold Distance ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Use ≤ so later (larger) cities win ties.