Created
March 7, 2025 01:46
-
-
Save shurane/d185934ce334118a34907818768088a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://leetcode.com/problems/network-delay-time/ | |
# Bellman-Ford shortest path algorithm | |
class Solution: | |
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: | |
dists = [float('inf') for _ in range(0, n + 1)] | |
dists[k] = 0 | |
for i in range(n-1): | |
# print(f"loop: {i}") | |
for u, v, w in times: | |
if dists[u] != float('inf'): | |
# if dists[u] + w < dists[v]: | |
# print(f"updating with lower weight: {u}-{v} with {dists[u] + w}") | |
dists[v] = min(dists[v], dists[u] + w) | |
# else: | |
# print(f"no existing edge to {u}, can't extend to {v}") | |
min_cost = 0 | |
for weight in dists[1:]: | |
if weight == float('inf'): | |
return -1 | |
min_cost = max(min_cost, weight) | |
return min_cost |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment