Matrix chain multiplication
On geeksforgeeks website I ran into the problem of <strong> multiplying a matrix chain .
There is a recursive solution for this problem, but the code is hard for me to understand. Actually, I am having problems with a certain line of code.
First of all, this is the code:
#include <stdio.h>
#include <limits.h>
//Matrix Ai has dimension p[i-1] x p[i] for i = 1...n
int MatrixChainOrder(int p[], int i, int j)
{
if(i == j)
return 0;
int k, min = INT_MAX, count;
for(k=i; k < j; k++) {
count = MatrixChainOrder(p,i,k) + MatrixChainOrder(p,k+1,j) + p[i-1]*p[k]*p[j];
if(count < min)
min = count;
}
return min;
}
int main() {
int arr[] = {1, 2, 3, 4, 3};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, 1, n-1));
getchar();
return 0;
}
Matrices: A = 1x2, B = 2x3, C = 3x4, D = 4x3
The line that is giving me some problem is this
count = MatrixChainOrder(p,i,k) + MatrixChainOrder(p,k+1,j) + p[i-1]*p[k]*p[j];
At the beginning of the for loop, i = 1
and j = 4
. So will evaluate as , which is obviously wrong, because matrix A can only be multiplied by B. I ran the code and nothing seems there was no result here because there was no result for the result, and also the same problem for the case ... p[i-1]*p[k]*p[j]
p[0]*p[1]*p[4] = 1x2x3
p[i-1]*p[k]*p[j]
i = 2, j = 4
Can someone enlighten me? I would be grateful if you could explain recursion to me in this code. I mean the way and the way it works.
source to share
The answer lies in what recursion does. Assuming that this means multiplication ABCD
, then iterating through the loop with i=1, j=4, k=1
represents performing that calculation with (A)(BCD)
. MatrixChainOrder(p,i,k)
computes the best computation (A)
, a 1x2
, and MatrixChainOrder(p,k+1,j)
computes the best computation (BCD)
, a 2x3
.
Finally, the term you're interested in p[i-1]*p[k]*p[j]
is the number of scalar multiplications to perform the final multiplication (A)
and (BCD)
.
source to share