Implementation of Matrix Chain Multiplication using Dynamic Programming in Java

Nickson Joram
Javarevisited
Published in
3 min readApr 23, 2021

--

We’ve discussed Matrix Chain Multiplication using Dynamic Programming in our last article ver clearly. In this article, we are going to implement it in Java.

Pseudocode

// Matrix A[i] has dimension dims[i-1] x dims[i] for i = 1..n
MatrixChainOrder(int dims[])
{
// length[dims] = n + 1
n = dims.length - 1;
// m[i,j] = Minimum number of scalar multiplications (i.e., cost)
// needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j]
// The cost is zero when multiplying one matrix
for (i = 1; i <= n; i++)
m[i, i] = 0;
for (len = 2; len <= n; len++) { // Subsequence lengths
for (i = 1; i <= n - len + 1; i++) {
j = i + len - 1;
m[i, j] = MAXINT;
for (k = i; k <= j - 1; k++) {
cost = m[i, k] + m[k+1, j] + dims[i-1]*dims[k]*dims[j];
if (cost < m[i, j]) {
m[i, j] = cost;
s[i, j] = k; // Index of the subsequence split that achieved minimal cost
}
}
}
}
}

Let’s implement the way we discussed in our previous article.

  1. Matrix.java
public class Matrix {
int row;
int col;

public Matrix(int row, int col) {
this.row = row;
this.col = col;
}
}

2. MatrixChain.java

public class MatrixChain {…

--

--