-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman_Ford.py
More file actions
65 lines (52 loc) · 2.01 KB
/
Copy pathBellman_Ford.py
File metadata and controls
65 lines (52 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import time
infinity = float("inf")
# (edge_weight, to_node)
def make_graph():
return {
'S': [(8, 'E'), (10, 'A')],
'A': [(2, 'C')],
'B': [(1, 'A')],
'C': [(-2, 'B')], # Bellman-Ford can handle negative edge weights
'D': [(-4, 'A'), (-1, 'C')],
'E': [(1, 'D')],
}
def Bellman_Ford(G, start):
# Bellman-Ford and Dijkstra's have the same end result:
# finding the shortest path from one source node to all other nodes
shortest_paths = {}
# Initialize all distances as infinity
for node in G:
shortest_paths[node] = infinity
# Distance to the start node is zero
shortest_paths[start] = 0
size = len(G) # Number of vertices |V|
# Bellman-Ford Algorithm takes at most V-1 iterations
# Time Complexity: O(|V| * |E|)
for _ in range(size - 1):
for node in G:
for edge in G[node]:
cost = edge[0]
to_node = edge[1]
# Bellman-Ford is NOT a greedy algorithm,
# so it works with negative edge weights
if shortest_paths[node] + cost < shortest_paths[to_node]:
shortest_paths[to_node] = shortest_paths[node] + cost
# Extra iteration to detect negative cycles
# Bellman-Ford and Dijkstra's both fail on graphs
# with negative cycles because no shortest path exists
for node in G:
for edge in G[node]:
cost = edge[0]
to_node = edge[1]
if shortest_paths[node] + cost < shortest_paths[to_node]:
return 'INVALID - negative cycle detected'
# Bellman-Ford guarantees the correct shortest paths
# (unlike Dijkstra's, which fails with negative edges)
return shortest_paths
start = 'S'
G = make_graph()
start_time = time.perf_counter()
shortest_paths = Bellman_Ford(G, start)
end_time = time.perf_counter()
print(f'Shortest path from {start}: {shortest_paths}')
print(f"Execution Time: {end_time - start_time:.6f} seconds")