Skip to content

Commit b382e42

Browse files
author
Hamid Gasmi
committedJul 7, 2022
#299: implement Bellman-Ford Algo part 1
1 parent 5ae9576 commit b382e42

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed
 

‎10-algo-ds-implementations/graph_fastest_path_bellman_ford.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,24 @@
3737

3838

3939
class Bellman_Ford(Fastest_Path_Base):
40-
40+
4141
def __compute_fastest_path (self):
42-
pass
42+
# Initializations
43+
self.__parent = [ -1 for _ in range(self.__graph.vertices_count) ]
44+
self.__distance = [ self.__max_distance for _ in range(self.__graph.vertices_count) ]
45+
46+
self.__distance[ self.__path_source_node ] = 0
47+
48+
for n in range(self.__graph.vertices_count):
49+
for v in range(self.__graph.vertices_count):
50+
if self.__distance[v] != self.__max_distance:
51+
for edge in self.__graph.adjacency_list[v]:
52+
candidate_distance = self.__distance[v] + edge.weight
53+
if self.__distance[edge.sink] > candidate_distance:
54+
self.__distance[edge.sink] = candidate_distance
55+
parents[edge.sink] = v
56+
reachable[edge.sink] = 1
57+
if n == self.__graph.vertices_count - 1:
58+
q.put(a_tuple.vertex)
4359

4460

‎10-algo-ds-implementations/graph_fastest_path_dijkstra_array.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
from typing import List
2-
from graph import Graph_Adjacency_List
3-
41
'''
52
Dijkstra's Algorithm
63
Input: Weighted Graph: G(V, E, W), s ∈ V
@@ -17,11 +14,11 @@
1714
- Dense graph (|E| = O(|V|^2)) --> T = O(|V|^2 + |V|^2) = O(|V|^2)
1815
- Sparce graph (|E| ~ |V|) --> T = O(|V|^2 + |V|) = O(|V|^2)
1916
- Space Complexity: O(|V|)
20-
- S(Parent list) + S(distance list) + S(visited nodes set) = O(|V| + |V| + |V|) = O(|V|)
21-
17+
- S(Parent list) + S(distance list) + S(visited nodes set) = O(|V| + |V| + |V|) = O(|V|)
2218
'''
2319

24-
Candidate = namedtuple('Candidate', ['distance', 'node'])
20+
from typing import List
21+
from graph import Graph_Adjacency_List
2522

2623
class Dijkstra_Heap_Queue:
2724
def __init__(self, graph: Graph_Adjacency_List, s: int):
@@ -61,7 +58,8 @@ def __get_closest_node(self, visited_nodes: set) -> int:
6158
min_distance = self.__distance[candidate]
6259

6360
return closest_node
64-
61+
62+
# O(|V|^2)
6563
def __compute_fastest_path (self):
6664
# Initialization
6765
self.__parent = [ -1 for _ in range(self.__graph.vertices_count) ] # O(|V|)
@@ -84,5 +82,4 @@ def __compute_fastest_path (self):
8482
self.__distance[ adjacent ] = candidate_distance
8583

8684
closest_node = self.__get_closest_node(visted_nodes) # O(|V|)
87-
88-
85+

0 commit comments

Comments
 (0)
Please sign in to comment.