|
| 1 | +import sys |
| 2 | +''' |
| 3 | +Dynamic Programming |
| 4 | +Implementation of Matrix Chain Multiplication |
| 5 | +Time Complexity: O(n^3) |
| 6 | +Space Complexity: O(n^2) |
| 7 | +''' |
| 8 | +def MatrixChainOrder(array): |
| 9 | + N=len(array) |
| 10 | + Matrix=[[0 for x in range(N)] for x in range(N)] |
| 11 | + Sol=[[0 for x in range(N)] for x in range(N)] |
| 12 | + for i in range(1,N): |
| 13 | + Matrix[i][i]=0 |
| 14 | + |
| 15 | + for ChainLength in range(2,N): |
| 16 | + for a in range(1,N-ChainLength+1): |
| 17 | + b = a+ChainLength-1 |
| 18 | + |
| 19 | + Matrix[a][b] = sys.maxsize |
| 20 | + for c in range(a , b): |
| 21 | + cost = Matrix[a][c] + Matrix[c+1][b] + array[a-1]*array[c]*array[b] |
| 22 | + if cost < Matrix[a][b]: |
| 23 | + Matrix[a][b] = cost |
| 24 | + Sol[a][b] = c |
| 25 | + return Matrix , Sol |
| 26 | +#Print order of matrix with Ai as Matrix |
| 27 | +def PrintOptimalSolution(OptimalSolution,i,j): |
| 28 | + if i==j: |
| 29 | + print("A" + str(i),end = " ") |
| 30 | + else: |
| 31 | + print("(",end = " ") |
| 32 | + PrintOptimalSolution(OptimalSolution,i,OptimalSolution[i][j]) |
| 33 | + PrintOptimalSolution(OptimalSolution,OptimalSolution[i][j]+1,j) |
| 34 | + print(")",end = " ") |
| 35 | + |
| 36 | +def main(): |
| 37 | + array=[30,35,15,5,10,20,25] |
| 38 | + n=len(array) |
| 39 | + #Size of matrix created from above array will be |
| 40 | + # 30*35 35*15 15*5 5*10 10*20 20*25 |
| 41 | + Matrix , OptimalSolution = MatrixChainOrder(array) |
| 42 | + |
| 43 | + print("No. of Operation required: "+str((Matrix[1][n-1]))) |
| 44 | + PrintOptimalSolution(OptimalSolution,1,n-1) |
| 45 | +if __name__ == '__main__': |
| 46 | + main() |
0 commit comments