|
| 1 | +package DynamicProgramming; |
| 2 | + |
| 3 | +// Matrix-chain Multiplication |
| 4 | +// Problem Statement |
| 5 | +// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n, |
| 6 | +// matrix Ai has dimension pi−1 ×pi |
| 7 | +// , fully parenthesize the product A1A2 ···An in a way that |
| 8 | +// minimizes the number of scalar multiplications. |
| 9 | + |
| 10 | +public class MatrixChainRecursiveTopDownMemoisation |
| 11 | +{ |
| 12 | + static int Memoized_Matrix_Chain(int p[]) { |
| 13 | + int n = p.length ; |
| 14 | + int m[][] = new int[n][n]; |
| 15 | + for (int i = 0; i < n; i++) { |
| 16 | + for (int j = 0; j < n; j++) { |
| 17 | + m[i][j] = Integer.MAX_VALUE; |
| 18 | + } |
| 19 | + } |
| 20 | + return Lookup_Chain(m, p, 1, n-1); |
| 21 | + } |
| 22 | + |
| 23 | + static int Lookup_Chain(int m[][],int p[],int i, int j) |
| 24 | + { |
| 25 | + if ( i == j ) |
| 26 | + { |
| 27 | + m[i][j] = 0; |
| 28 | + return m[i][j]; |
| 29 | + } |
| 30 | + if ( m[i][j] < Integer.MAX_VALUE ) |
| 31 | + { |
| 32 | + return m[i][j]; |
| 33 | + } |
| 34 | + |
| 35 | + else |
| 36 | + { |
| 37 | + for ( int k = i ; k<j ;k++) |
| 38 | + { |
| 39 | + int q = Lookup_Chain(m, p,i , k ) + Lookup_Chain(m, p, k+1 , j) + (p[i-1] * p[k] * p[j]); |
| 40 | + if ( q < m[i][j] ) |
| 41 | + { |
| 42 | + m[i][j] = q; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + return m[i][j]; |
| 47 | + } |
| 48 | + // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively |
| 49 | + // output should be Minimum number of multiplications is 38 |
| 50 | + public static void main (String[] args) |
| 51 | + { |
| 52 | + |
| 53 | + int arr[] = { 1, 2, 3, 4 ,5}; |
| 54 | + System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)); |
| 55 | + } |
| 56 | +} |
0 commit comments