Skip to content

Commit e391a24

Browse files
committed
feat: 0094 python solution SPFA
1 parent ca40c94 commit e391a24

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

problems/kamacoder/0094.城市间货物运输I-SPFA.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,44 @@ public class Main {
425425
```
426426

427427
### Python
428-
428+
```Python
429+
import collections
430+
431+
def main():
432+
n, m = map(int, input().strip().split())
433+
edges = []
434+
for _ in range(m):
435+
src, dest, weight = map(int, input().strip().split())
436+
edges.append([src, dest, weight])
437+
438+
minDist = [float("inf")] * (n + 1)
439+
minDist[1] = 0
440+
que = collections.deque([1])
441+
visited = [False] * (n + 1)
442+
visited[1] = True
443+
444+
while que:
445+
cur = que.popleft()
446+
visited[cur] = True
447+
updated = False
448+
for src, dest, weight in edges:
449+
if minDist[src] != float("inf") and minDist[src] + weight < minDist[dest]:
450+
minDist[dest] = minDist[src] + weight
451+
updated = True
452+
if visited[dest] == False:
453+
que.append(dest)
454+
visited[dest] = True
455+
456+
if not updated:
457+
break
458+
459+
if minDist[-1] == float("inf"):
460+
return "unconnected"
461+
return minDist[-1]
462+
463+
if __name__ == "__main__":
464+
print(main())
465+
```
429466
### Go
430467

431468
### Rust

0 commit comments

Comments
 (0)