-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBellmanFord.py
42 lines (35 loc) · 895 Bytes
/
BellmanFord.py
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
import GraphLib
import DirectedEdge, ShortestPath
# negative cycle
with open('tinyEWDnc.txt', 'r') as f:
V = int(f.readline().strip())
E = int(f.readline().strip())
text = f.read()
f.close()
Gnc = GraphLib.EdgeWeightedDigraph(V)
lines = text.split('\n')
for line in lines[:-1]: # last line is empty
l = line.split()
v = int(l[0])
w = int(l[1])
weight = float(l[2])
Gnc.addEdge(DirectedEdge.DEdge(v, w, weight))
# negative weight
with open('tinyEWDn.txt', 'r') as f:
V = int(f.readline().strip())
E = int(f.readline().strip())
text = f.read()
f.close()
Gn = GraphLib.EdgeWeightedDigraph(V)
lines = text.split('\n')
for line in lines[:-1]: # last line is empty
l = line.split()
v = int(l[0])
w = int(l[1])
weight = float(l[2])
Gn.addEdge(DirectedEdge.DEdge(v, w, weight))
bn = ShortestPath.BellmanFord(Gn, 0)
bn.hasNegativeCycle()
bn.hasPathTo(6)
bn.pathTo(6)
bn.distTo(6)