forked from davidoiknine/algo_inclass_S4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FloydBellmanFord.py
96 lines (77 loc) · 2.39 KB
/
FloydBellmanFord.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*- coding: utf-8 -*-
"""
Digraph Shortest Paths
Floyd + Bellman-Ford
"""
from algopy import graph
inf = float('inf')
def Floyd(G):
n = G.order
dist = []
p = []
for x in range(n):
dist.append([])
p.append([])
for y in range(n):
if (x, y) in G.costs:
dist[x].append(G.costs[(x, y)])
else:
dist[x].append(inf)
p[x].append(x)
for i in range(n):
for x in range(n):
for y in range(n):
if dist[x][i] + dist[i][y] < dist[x][y]:
dist[x][y] = dist[x][i] + dist[i][y]
p[x][y] = p[i][y]
return (dist, p)
#------------------------------------------------------------------------------
def BellmanFord(G, src):
"""
returns a tuple (boolean, dist, p):
boolean = is there a negative circuit
"""
dist = [inf] * G.order
dist[src] = 0
p = [-1] * G.order
n = G.order
changes = True
while n > 0 and changes:
changes = False
for x in range(G.order-1, -1, -1):
if dist[x] != inf:
for y in G.adjlists[x]:
if dist[x] + G.costs[(x, y)] < dist[y]:
dist[y] = dist[x] + G.costs[(x, y)]
p[y] = x
changes = True
n -= 1
return (changes, dist, p)
#------------------------------------------------------------------------------
# optimization?
from algopy import queue
def BellmanFordOpti(G, src):
dist = [inf] * G.order
dist[src] = 0
p = [-1] * G.order
n = G.order
q = queue.Queue()
q.enqueue(src)
inQueue = [False] * G.order
inQueue[src] = True
q2 = queue.Queue()
while n > 0 and not q.isempty():
x = q.dequeue()
inQueue[x] = False
for y in G.adjlists[x]:
if dist[x] + G.costs[(x, y)] < dist[y]:
dist[y] = dist[x] + G.costs[(x, y)]
p[y] = x
if not inQueue[y]:
q2.enqueue(y)
inQueue[y] = True
if q.isempty(): # level change
q = q2
q2 = queue.Queue()
n -= 1
return (not q.isempty(), dist, p)