Java:通过递归的方矩阵乘法

Java:通过递归的方矩阵乘法,java,algorithm,recursion,matrix,Java,Algorithm,Recursion,Matrix,我需要编写一个递归方法,将2个大小为n的平方矩阵乘以n。 它需要在θ^3时间内运行,但不是Strassen算法。 我已经写了一个方法,但是我得到了一个堆栈溢出 Matrix A is Matrix B is 1 2 1 0 3 2 3 0 2 3 2 0 2 1 2 0 1 2 1 0 3 2 3 0 这两个矩阵都是int[]。以下是我编写的代码: public int[][] ncubed(int [][]A, int

我需要编写一个递归方法,将2个大小为n的平方矩阵乘以n。 它需要在θ^3时间内运行,但不是Strassen算法。 我已经写了一个方法,但是我得到了一个堆栈溢出

Matrix A is       Matrix B is
1 2 1 0           3 2 3 0
2 3 2 0           2 1 2 0
1 2 1 0           3 2 3 0
这两个矩阵都是int[]。以下是我编写的代码:

public int[][] ncubed(int [][]A, int [][]B){
    int w = A.length;
    int [][] C = new int[w][w];
    if (w==1){ 
        C[0][0] = A[0][0] * B[0][0];
    }
    else{
    int [][]A1 = partition(1,A);
    int [][]A2 = partition(2,A);
    int [][]A3 = partition(3,A);
    int [][]A4 = partition(4,A);
    int [][]B1 = partition(1,B);
    int [][]B2 = partition(2,B);
    int [][]B3 = partition(3,B);
    int [][]B4 = partition(4,B);
    int [][]C1 = partition(1,C);
    int [][]C2 = partition(2,C);
    int [][]C3 = partition(3,C);
    int [][]C4 = partition(4,C);

    C1 = add(ncubed(A1,B1),ncubed(A2,B3));
    C2 = add(ncubed(A1,B2),ncubed(A2,B4));
    C3 = add(ncubed(A3,B1),ncubed(A4,B3));
    C4 = add(ncubed(A3,B2),ncubed(A4,B4));

    join(C1, C, 0 , 0);
    join(C2, C, w/2 , 0);
    join(C3, C, 0, w/2);
    join(C4, C, w/2, w/2);

    }
    return C;
}

public int [][] partition(int quadrant, int[][] array){
    int n = array.length;
    int[][] Q = new int[array.length][array.length];
    if(quadrant>4 || quadrant<1) return null;
    switch(quadrant){
    case(1): 
        for(int i = 0; i<(n/2); i++){
            for(int j = 0; j<(n/2); j++){
                Q[i][j] = array[i][j];
            }
        }
        break;
    case(2):
        for(int i = n/2; i<n; i++){
            for(int j = 0; j<(n/2); j++){
                Q[i][j] = array[i][j];
            }
        }
        break;
    case(3):
        for(int i = 0; i<(n/2); i++){
            for(int j = (n/2); j<n; j++){
                Q[i][j] = array[i][j];
            }
        }
        break;
    case(4):
        for(int i = (n/2); i<n; i++){
            for(int j = (n/2); j<n; j++){
                Q[i][j] = array[i][j];
            }
        }
        break;
    }
    return Q;
}
方法add和join工作得很好,因为我已经对它们进行了测试,所以不在该部分。 我就是不能用实际的计算方法——矩阵乘法法来解决我的问题。
如果有人能帮助我理解我做错了什么,或者用上面的规范告诉我另一种方法,那就太棒了。谢谢你的帮助。

这个简单的方法会给你3次时间-你退房了吗


如果做不到这一点,你有没有看问题?

这一定是我见过的最不自然的递归问题之一。我能想到的最好方法是将矩阵的顶行作为行向量,相乘,然后对剩余的行进行递归调用,但这也可能是迭代的。您实现了Strassen吗?你能不玩这个把戏来玩n立方体游戏吗?我要做的是做一个不是strassen的n立方方法。我已经实现了strassen。我必须递归地编写它。我已经看过那个三重for循环,我不允许使用它。我也看到了另外两个问题,但它们没有得到准确的回答。这是一个显示图片和你链接到单词的书中的文本的图片,这是我需要写的相同方法,也是同一本书。但是回答这个问题的人基本上又写了一次伪代码,我理解。我现在已经尝试将其写入代码,这就是我在上面发布的内容:/