使用分治算法计算矩阵c = a * b,首先假设三个矩阵都是nn的矩阵,其中n为2的幂。然后把a和b矩阵分别划分成四个(n/2)(n/2)的子矩阵。c也分成四个子矩阵。然后递归函数当每个子矩阵都分成单个数据时输出
我用的在递归函数中定义了12个数组,其实有更简单的方法,但我还没想出来,如果有小伙伴知道请指点一二。
首先我的递归函数如下:
public static int[][] souare_matrix_mul_tily(int[][] a,int[][] b)
{
int n = a.length ;
int[][] c = new int[n][n];
int[][]a11 = new int[n/2][n/2];
int[][]a12 = new int[n/2][n/2];
int[][]a21 = new int[n/2][n/2];
int[][]a22 = new int[n/2][n/2];
int[][]b11 = new int[n/2][n/2];
int[][]b12 = new int[n/2][n/2];
int[][]b21 = new int[n/2][n/2];
int[][]b22 = new int[n/2][n/2];
int[][]c11 = new int[n/2][n/2];
int[][]c12 = new int[n/2][n/2];
int[][]c21 = new int[n/2][n/2];
int[][]c22 = new int[n/2][n/2];
if (n == 1)
{
c[0][0] = a[0][0]*b[0][0];
}
else
{
for(int i =0 ,k = 0; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0 ,s = 0;(j<n/2)&&(s<n/2);j++,s++)
{
a11[i][j] = a[k][s];
}
for(int i =0,k =n/2;(i<n/2)&&(k<n);i++,k++)
for(int j =0,s = 0 ;j<n/2&&s<n/2;j++,s++)
{
a21[i][j] = a[k][s];
}
for(int i =0,k=0 ; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0,s=n/2 ;(j<n/2)&&(s<n);j++,s++)
{
a12[i][j] = a[k][s];
}
for(int i =0,k = n/2 ; (i<n/2)&&(k<n);i++,k++)
for(int j =0,s = n/2 ;(j<n/2)&&(s<n);j++,s++)
{
a22[i][j] = a[k][s];
}
for(int i =0 ,k=0; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0 ,s = 0;(j<n/2)&&(s<n/2);j++,s++)
{
b11[i][j] = b[k][s];
}
for(int i =0,k =n/2;(i<n/2)&&(k<n);i++,k++)
for(int j =0,s = 0 ;(j<n/2)&&(s<n/2);j++,s++)
{
b21[i][j] = b[k][s];
}
for(int i =0,k=0 ; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0,s=n/2 ;(j<n/2)&&(s<n);j++,s++)
{
b12[i][j] = b[k][s];
}
for(int i =0,k = n/2 ; (i<n/2)&&(k<n);i++,k++)
for(int j =0,s = n/2 ;(j<n/2)&&(s<n);j++,s++)
{
b22[i][j] = b[k][s];
}
//需要定义矩阵加法函数
c11 = sum(souare_matrix_mul_tily(a11,b11) , souare_matrix_mul_tily(a12,b21));
c12 = sum(souare_matrix_mul_tily(a11,b12),souare_matrix_mul_tily(a12,b22));
c21 = sum(souare_matrix_mul_tily(a22,b21),souare_matrix_mul_tily(a21,b12));
c22 = sum(souare_matrix_mul_tily(a21,b12),souare_matrix_mul_tily(a22,b22));
for(int i =0 ,k=0; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0 ,s = 0;(j<n/2)&&(s<n/2);j++,s++)
{
c[k][s]= c11[i][j] ;
}
for(int i =0,k =n/2;(i<n/2)&&(k<n);i++,k++)
for(int j =0,s = 0 ;(j<n/2)&&(s<n/2);j++,s++)
{
c[k][s]= c21[i][j];
}
for(int i =0,k=0 ; (i<n/2)&&(k<n/2);i++,k++)
for(int j =0,s=n/2 ;(j<n/2)&&(s<n);j++,s++)
{
c[k][s]= c12[i][j] ;
}
for(int i =0,k = n/2 ; (i<n/2)&&(k<n);i++,k++)
for(int j =0,s = n/2 ;(j<n/2)&&(s<n);j++,s++)
{
c[k][s] = c22[i][j];
}
}
return c;
其中sum函数是做矩阵加法运算的
public static int[][] sum(int[][]a,int[][]b)
{
int n = a.length;
int[][]c = new int[n][n];
for(int i = 0;i<n ;i++)
for(int j=0;j<n;j++)
{
c[i][j] = a[i][j]+b[i][j];
}
return c;
}```
以上矩阵都有一个前提,就是他们都是同维的,矩阵行列不一致的情况我没有试过,有兴趣的小伙伴可以尝试一下。