From a3075308faacf803abe2e1ad6e89b5c3c5252c1c Mon Sep 17 00:00:00 2001 From: kyshen Date: Wed, 4 Sep 2024 23:00:44 +0800 Subject: [PATCH] feat: 0094 bellman-ford python solution --- .../kamacoder/0094.城市间货物运输I.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/kamacoder/0094.城市间货物运输I.md b/problems/kamacoder/0094.城市间货物运输I.md index 45ca1313..3737fe01 100644 --- a/problems/kamacoder/0094.城市间货物运输I.md +++ b/problems/kamacoder/0094.城市间货物运输I.md @@ -451,6 +451,33 @@ public class Main { ``` ### Python +```Python +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 # 起点处距离为0 + + for i in range(1, n): + 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 not updated: # 若边不再更新,即停止回圈 + break + + if minDist[-1] == float("inf"): # 返还终点权重 + return "unconnected" + return minDist[-1] + +if __name__ == "__main__": + print(main()) +``` ### Go