-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapsp_floyd_warshall.py
69 lines (61 loc) · 2.38 KB
/
apsp_floyd_warshall.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
v = 1 # number of vertices
INF = float('inf')
# Regular variant - basic form
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = min(D[i][j], D[i][k]+D[k][j])
# Transitive closure - reachability
g = [set() for _ in range(v)]
D = [[int(j in g[i]) for j in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] |= D[i][k]&D[k][j]
# Minimax - for MST
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = min(D[i][j], max(D[i][k], D[k][j]))
# Maximin - for MaxST
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = max(D[i][j], min(D[i][k], D[k][j]))
# Negative cycle detection - version 1
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = min(D[i][j], D[i][k]+D[k][j])
for i in range(v):
for j in range(v):
for k in range(v):
if D[i][j] == -INF: break
if D[i][k] != INF and D[k][j] != INF and D[k][k] < 0: D[i][j] = -INF
# Negative cycle detection - version 2
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for i in range(v): D[i][i] = INF
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = min(D[i][j], D[i][k]+D[k][j])
cyc = [i for i in range(v) if D[i][i]<0]
# Positive cycle detection
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
for i in range(v): D[i][i] = INF
for k in range(v):
for i in range(v):
for j in range(v): D[i][j] = min(D[i][j], D[i][k]+D[k][j])
cyc = [i for i in range(v) if 0<=D[i][i]<INF]
# Print path
g = [{} for _ in range(v)]
D = [[g[i][j] if j in g[i] else INF for j in range(v)] for i in range(v)]
p = [[i for _ in range(v)] for i in range(v)]
for k in range(v):
for i in range(v):
for j in range(v):
if D[i][j]>(new:=D[i][k]+D[k][j]): D[i][j], p[i][j] = new, p[k][j]