Network Delay Time
LeetCode 743 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Dijkstra from k; answer = max distance.
ನಾನು Network Delay Time (LeetCode 743) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / Dijkstra ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
The signal reaches each node along its shortest path from k, so the time for everyone to receive it is the largest shortest-path distance. Dijkstra computes all of them.
Approach
- 1
Adjacency list of weighted directed edges.
- 2
Min-heap starting with (0, k).
- 3
Relax edges; push improved distances.
- 4
Max of dist[1..n], or −1 if any is ∞.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
DijkstraPythonO(E log V) time
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj = defaultdict(list)
for u,v,w in times:
adj[u].append((v,w))
dist = [float("inf")]*(n+1)
dist[k]=0
min_heap =[(0,k)]
while min_heap:
cost,node = heapq.heappop(min_heap)
for adj_node,wt in adj[node]:
if dist[node]+wt < dist[adj_node]:
dist[adj_node]=dist[node]+wt
heapq.heappush(min_heap,(dist[node]+wt,adj_node))
min_time = max(dist[1:])
return min_time if min_time!=float("inf") else -1Network Delay Time — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Network Delay Time ಹಿಂದಿನ intuition ಏನು?
The signal reaches each node along its shortest path from k, so the time for everyone to receive it is the largest shortest-path distance. Dijkstra computes all of them.
Network Delay Time (LeetCode 743) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Adjacency list of weighted directed edges. 2. Min-heap starting with (0, k). 3. Relax edges; push improved distances. 4. Max of dist[1..n], or −1 if any is ∞.
Network Delay Time ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(E log V). Space: O(V + E). (Accepted approach: Dijkstra.)
Network Delay Time ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Nodes are 1-indexed; ignore dist[0].