1+ // Dynamic Programming Python implementation of Matrix
2+ // Chain Multiplication.
3+ public class MatrixChainMultiplication {
4+ // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
5+ static int MatrixChainOrder (int p [], int n ) {
6+ /* For simplicity of the program, one extra row and one
7+ extra column are allocated in m[][]. 0th row and 0th
8+ column of m[][] are not used */
9+ int m [][] = new int [n ][n ];
10+
11+ int i , j , k , L , q ;
12+
13+ /* m[i,j] = Minimum number of scalar multiplications needed
14+ to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where
15+ dimension of A[i] is p[i-1] x p[i] */
16+
17+ // cost is zero when multiplying one matrix.
18+ for (i = 1 ; i < n ; i ++)
19+ m [i ][i ] = 0 ;
20+
21+ // L is chain length.
22+ for (L =2 ; L <n ; L ++) {
23+ for (i =1 ; i <n -L +1 ; i ++) {
24+ j = i +L -1 ;
25+ if (j == n ) continue ;
26+ m [i ][j ] = Integer .MAX_VALUE ;
27+ for (k =i ; k <=j -1 ; k ++) {
28+ // q = cost/scalar multiplications
29+ q = m [i ][k ] + m [k +1 ][j ] + p [i -1 ]*p [k ]*p [j ];
30+ if (q < m [i ][j ])
31+ m [i ][j ] = q ;
32+ }
33+ }
34+ }
35+ return m [1 ][n -1 ];
36+ }
37+
38+ // Driver program to test above function
39+ public static void main (String args []) {
40+ int arr [] = new int [] {1 , 2 , 3 , 4 };
41+ int size = arr .length ;
42+ System .out .println ("Minimum number of multiplications is " +
43+ MatrixChainOrder (arr , size ));
44+ }
45+ }
0 commit comments