From 9e0982257cbe0dc7cede9162d5c414aab5f06eb2 Mon Sep 17 00:00:00 2001 From: Spectre Date: Tue, 27 May 2025 20:50:49 +0200 Subject: [PATCH] bellman --- programmation_dynamique/bellman/main.py | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 programmation_dynamique/bellman/main.py diff --git a/programmation_dynamique/bellman/main.py b/programmation_dynamique/bellman/main.py new file mode 100644 index 0000000..f2a0dca --- /dev/null +++ b/programmation_dynamique/bellman/main.py @@ -0,0 +1,28 @@ +def bellman_ford(graphe, sommet): + distance = {sommet: float("inf") for sommet in graphe} + distance[sommet] = 0 + + for i in range(len(graphe) - 1): + for u in graphe: + for v, coef in graphe[u]: + if distance[u] + coef < distance[v]: + distance[v] = distance[u] + coef + + for u in graphe: + for v, coef in graphe[u]: + if distance[u] + coef < distance[v]: + raise ValueError("Cycle négatif détecté") + + return distance + + +if __name__ == "__main__": + graphe = { + "A": [("G", 8), ("H", 4)], + "G": [("H", 1), ("L", 2)], + "H": [("L", 5), ("E", 7)], + "L": [("E", -2)], + "E": [], + } + distances = bellman_ford(graphe, "A") + print(distances)