根据算法导论里的矩阵乘法递归的思想实现
#if 0
int a[8][8] = { {1,2,3,4,5,6,7,8},
{2,3,4,5,6,7,8,9},
{3,4,5,6,7,8,9,10},
{4,5,6,7,8,9,10,11},
{5,6,7,8,9,10,11,12},
{6,7,8,9,10,11,12,13},
{7,8,9,10,11,12,13,14},
{8,9,10,11,12,13,14,15}
};
int b[8][8] = { {10,11,12,13,14,15,16,17},
{11,12,13,14,15,16,17,18},
{12,13,14,15,16,17,18,19},
{13,14,15,16,17,18,19,20},
{14,15,16,17,18,19,20,21},
{15,16,17,18,19,20,21,22},
{16,17,18,19,20,21,22,23},
{17,18,19,20,21,22,23,24}
};
#endif
#include
#define MAX_SIZE 100
int a[MAX_SIZE][MAX_SIZE];
int b[MAX_SIZE][MAX_SIZE];
int c[MAX_SIZE][MAX_SIZE];
void matrix_multi(int a[][MAX_SIZE], int b[][MAX_SIZE], int c[][MAX_SIZE], int size)
{
int i, j;
for( i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
int k;
int sum = 0;
for( k = 0; k < size; k++)
{
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
}
void matrix_multi_recursive( int a[][MAX_SIZE], int m, int n, int b[][MAX_SIZE], int p, int q, int size, int c[][MAX_SIZE])
{
if(size == 1)
{
// printf("m: %d, n: %d, p: %d, q: %d\n", m, n, p, q);
c[m][q] += a[m][n] * b[p][q];
}
else
{
int half_size = size >> 1;
matrix_multi_recursive(a, m, n, b, p, q, half_size, c);
matrix_multi_recursive(a, m, n + half_size, b, p + half_size, q, half_size, c);
matrix_multi_recursive(a, m, n, b, p, q + half_size, half_size, c);
matrix_multi_recursive(a, m, n + half_size, b, p + half_size, q + half_size, half_size, c);
matrix_multi_recursive(a, m + half_size, n, b, p, q, half_size, c);
matrix_multi_recursive(a, m + half_size, n + half_size, b, p + half_size, q, half_size, c);
matrix_multi_recursive(a, m + half_size, n, b, p, q + half_size, half_size, c);
matrix_multi_recursive(a, m + half_size, n + half_size, b, p + half_size, q + half_size, half_size, c);
}
}
void print(int c[][MAX_SIZE], int size)
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
}
int main(void)
{
int i, j;
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
a[i][j] = 1 + i + j;
b[i][j] = 10 + i + j;
c[i][j] = 0;
}
}
print(a, 8);
print(b, 8);
matrix_multi(a,b,c, 8);
print(c, 8);
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
c[i][j] = 0;
}
}
matrix_multi_recursive(a, 0, 0, b, 0, 0, 8, c);
print(c, 8);
return 0;
}