Skip to content

Commit 5ae9576

Browse files
author
Hamid Gasmi
committed
#299: start Bellman-Form implementation
1 parent 2a1028c commit 5ae9576

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import List
2+
from graph import Graph_Adjacency_List
3+
4+
'''
5+
Fastest Path base
6+
7+
Implementation Assumptions:
8+
- Directed graph
9+
- Edges number starts from 0 (zero-based numbering)
10+
- Edges list is valid
11+
- 0 <= edge.source, edge.sink < vertices_count for any edge in edges list
12+
- It does not have duplicates
13+
14+
'''
15+
16+
class Fastest_Path_Base:
17+
def __init__(self, graph: Graph_Adjacency_List, s: int):
18+
self.__max_distance = 10**7
19+
20+
self.__graph = graph
21+
22+
self.__path_source_node = s
23+
self.__parent = []
24+
self.__distance = []
25+
26+
def fastest_distance_to(self, dest: int) -> int:
27+
if len(self.__distance) == 0:
28+
self.__compute_fastest_path()
29+
30+
return self.__distance[dest]
31+
32+
def fastest_path_to(self, dest: int) -> List[int]:
33+
if len(self.__distance) == 0:
34+
self.__compute_fastest_path()
35+
36+
v = dest
37+
reversed_path = []
38+
while v != -1:
39+
reversed_path.append(v)
40+
v = self.__parent[v]
41+
42+
return reversed_path[::-1]
43+
44+
# abstract method
45+
def __compute_fastest_path (self):
46+
pass
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''
2+
Input: G(V, E, W) a directed graph without a negative cycle, s ∈ V
3+
- -Infinity < We < +Infinity for any e in E
4+
- G MUST not have a negative cycle => min_dist(u, v) = -Infinity for any { u, v } ⊆ V
5+
- G does not have negative cycle => G is Directed graph
6+
E.g.
7+
G(V, E, W) an undirected graph with 2 vertices and 1 edge with weight is negative
8+
min_distance(1, 2) = - Infinity
9+
-1
10+
1 ------- 2
11+
12+
Output:
13+
- fastest path from s to any v in V
14+
- fastest path distances from s to any v in V
15+
16+
Question: Why Dijskra's algorithm doesn't work in this case?
17+
-2
18+
3 ---- > 4 Dijkstra(1, 4) = 2
19+
^ ^ Bellman-Ford(1, 4) = 1
20+
3| | 1
21+
1 -----> 2
22+
1
23+
24+
Time & Space Complexity:
25+
- Time Complexity:
26+
- Space Complexity:
27+
28+
Implementation Assumptions:
29+
- Zero-based numbering: Edges number starts from 0
30+
- Edges list is valid
31+
- 0 <= edge.source, edge.sink < vertices_count for any edge in edges list
32+
- It does not have duplicates
33+
- It doesn't have a negative cycle
34+
35+
'''
36+
from graph_fastest_path_base import Fastest_Path_Base
37+
38+
39+
class Bellman_Ford(Fastest_Path_Base):
40+
41+
def __compute_fastest_path (self):
42+
pass
43+
44+

0 commit comments

Comments
 (0)