Skip to content

Commit 0e480f6

Browse files
authored
Add Matrix Chain Multiplication optimised approach
1 parent 4a03f42 commit 0e480f6

File tree

1 file changed

+64
-0
lines changed
  • src/main/java/com/thealgorithms/misc

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Dynamic Programming Java implementation of Matrix
2+
// Chain Multiplication.
3+
// See the Cormen book for details of the following
4+
// algorithm
5+
import java.util.*;
6+
import java.io.*;
7+
class MatrixChainMultiplication
8+
{
9+
10+
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
11+
static int MatrixChainOrder(int p[], int n)
12+
{
13+
/* For simplicity of the
14+
program, one extra row and
15+
one extra column are allocated in m[][]. 0th row
16+
and 0th column of m[][] are not used */
17+
int m[][] = new int[n][n];
18+
19+
int i, j, k, L, q;
20+
21+
/* m[i, j] = Minimum number of scalar
22+
multiplications needed to compute the matrix
23+
A[i]A[i+1]...A[j] = A[i..j] where
24+
dimension of A[i] is p[i-1] x p[i] */
25+
26+
// cost is zero when multiplying one matrix.
27+
for (i = 1; i < n; i++)
28+
m[i][i] = 0;
29+
30+
// L is chain length.
31+
for (L = 2; L < n; L++)
32+
{
33+
for (i = 1; i < n - L + 1; i++)
34+
{
35+
j = i + L - 1;
36+
if (j == n)
37+
continue;
38+
m[i][j] = Integer.MAX_VALUE;
39+
for (k = i; k <= j - 1; k++)
40+
{
41+
// q = cost/scalar multiplications
42+
q = m[i][k] + m[k + 1][j]
43+
+ p[i - 1] * p[k] * p[j];
44+
if (q < m[i][j])
45+
m[i][j] = q;
46+
}
47+
}
48+
}
49+
50+
return m[1][n - 1];
51+
}
52+
53+
// Driver code
54+
public static void main(String args[])
55+
{
56+
int arr[] = new int[] { 1, 2, 3, 4 };
57+
int size = arr.length;
58+
59+
System.out.println(
60+
"Minimum number of multiplications is "
61+
+ MatrixChainOrder(arr, size));
62+
}
63+
}
64+
/* This code is contributed by Rajat Mishra*/

0 commit comments

Comments
 (0)