feat: 0094 python solution SPFA

This commit is contained in:
kyshen
2024-09-06 22:39:29 +08:00
parent ca40c94392
commit e391a24729

View File

@ -425,7 +425,44 @@ public class Main {
```
### Python
```Python
import collections
def main():
n, m = map(int, input().strip().split())
edges = []
for _ in range(m):
src, dest, weight = map(int, input().strip().split())
edges.append([src, dest, weight])
minDist = [float("inf")] * (n + 1)
minDist[1] = 0
que = collections.deque([1])
visited = [False] * (n + 1)
visited[1] = True
while que:
cur = que.popleft()
visited[cur] = True
updated = False
for src, dest, weight in edges:
if minDist[src] != float("inf") and minDist[src] + weight < minDist[dest]:
minDist[dest] = minDist[src] + weight
updated = True
if visited[dest] == False:
que.append(dest)
visited[dest] = True
if not updated:
break
if minDist[-1] == float("inf"):
return "unconnected"
return minDist[-1]
if __name__ == "__main__":
print(main())
```
### Go
### Rust