Skip to content

Commit 44795ec

Browse files
committed
Bellman-Ford algorithm
1 parent 91e24c2 commit 44795ec

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

graphs/bellman–ford/graph.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
# Bellman-Ford algorithm
3+
# Find shortest paths from one vertex,
4+
# to all other vertices in weighted graph.
5+
# Runtime O(V*E)
6+
7+
class Graph:
8+
def __init__(self):
9+
self.vertices: list = []
10+
self.edges: list = []
11+
self.distance: dict = {}
12+
self.prev: dict = {}
13+
14+
def add_vertex(self, label: str):
15+
self.vertices.append(label)
16+
self.distance[label] = None
17+
self.prev[label] = None
18+
19+
def add_edge(self, label1: str, label2: str, weight: int):
20+
self.edges.append([label1, label2, weight])
21+
22+
def bellman_ford(self, source: str):
23+
self.distance[source] = 0
24+
25+
for _ in range(len(self.vertices)):
26+
27+
for edge in self.edges:
28+
label1: str = edge[0]
29+
label2: str = edge[1]
30+
weight: int = edge[2]
31+
32+
if self.distance[label1] is None:
33+
continue
34+
if self.distance[label2] is None:
35+
self.distance[label2] = self.distance[label1] + weight
36+
self.prev[label2] = label1
37+
continue
38+
if self.distance[label1] + weight < self.distance[label2]:
39+
self.distance[label2] = self.distance[label1] + weight
40+
self.prev[label2] = label1
41+
continue
42+
43+
def print_distances(self, source: str):
44+
for v in self.vertices:
45+
if v != source:
46+
distance: int = self.distance[v]
47+
print(f'Distance from {source} to {v} is {distance}')

0 commit comments

Comments
 (0)