-
Notifications
You must be signed in to change notification settings - Fork 0
/
MatrixMultiplicationRecur.cpp
45 lines (38 loc) · 1.05 KB
/
MatrixMultiplicationRecur.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* A naive recursive implementation that simply
follows the above optimal substructure property */
#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;
int min = INT_MAX;
int count;
// place parenthesis at different places between first
// and last matrix, recursively calculate count of
// multiplications for each parenthesis placement and
// return the minimum count
for (k = i+1; k <j; k++)
{
count = MatrixChainOrder(p, i, k) +
MatrixChainOrder(p, k, j) +
p[i]*p[k]*p[j];
printf("%d", p[i]*p[k]*p[j]);
if (count < min)
min = count;
}
// Return minimum count
return min;
}
// Driver program to test above function
int main()
{
int arr[] = {1, 2, 3};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainOrder(arr, 0, n-1));
getchar();
return 0;
}