-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFastClosure.py
58 lines (48 loc) · 1.33 KB
/
FastClosure.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
from MinPlus import minPlus, matrixAdd
import copy
inf = 1000000
def nextEven(n):
return n + n % 2
def padMatrix(Y):
X = [i for i in Y]
initWidth = len(X[0])
initHeight = len(X)
width = nextEven(len(X))
height = nextEven(len(X[0]))
n = max(width, height)
for i in range(0, len(X)):
for j in range(0, n-initWidth):
X[i].append(inf)
for i in range(0, n-initHeight):
X.append([inf] * n)
for i in range(0, len(X)):
for j in range(0, len(X[i])):
if i == j:
X[i][j] = 0
return X
def fastClosure(Y):
if(len(Y) == 1):
return [[0]]
initLength = len(Y)
X = padMatrix(Y)
padMatrix(X)
# divide the matrix into four quadrants
h = len(X)//2
A = [r[:h] for r in X[:h]]
B = [r[h:] for r in X[:h]]
C = [r[:h] for r in X[h:]]
D = [r[h:] for r in X[h:]]
T1 = fastClosure(D)
T2 = minPlus(B, T1)
E = fastClosure(matrixAdd(A, minPlus(T2, C)))
F = minPlus(E, T2)
T3 = minPlus(T1, C)
G = minPlus(T3, E)
H = matrixAdd(T1, minPlus(G, T2))
newMatrixLeft = E + G
newMatrixRight = F + H
for i in range(0, len(newMatrixLeft)):
newMatrixLeft[i] += newMatrixRight[i]
return [r[:initLength] for r in newMatrixLeft[:initLength]]
def fastClosureAPSP(A):
return fastClosure(A)