【问题标题】:Java: Square Matrix Multiplication by means of recursionJava:通过递归的方阵乘法
【发布时间】:2014-06-03 00:56:54
【问题描述】:

我需要编写一个递归方法,将 2 个方阵(大小为 n×n)相乘。 它需要在 theta(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 工作正常,因为我已经测试过它们,所以它不在那个部分。 我只是无法在实际的 ncubed 方法(矩阵乘法方法)中找出我的问题。 如果有人能够帮助我理解我做错了的事情,或者向我展示了另一种使用顶部说明的规范来做到这一点的方法,那就太棒了。感谢您的帮助。

【问题讨论】:

  • 这一定是我见过的最不自然的递归问题之一。我能想到的最好的方法是将矩阵的第一行视为行向量,相乘,然后对剩余的行进行递归调用,但这也可能是迭代的。
  • 您实施了 Strassen 吗?你会通过不做这个把戏来玩 n 个立方体吗?
  • 我必须做的规范是做一个不是 strassen 的 N 立方方法。我已经实现了 strassen。

标签: java algorithm recursion matrix


【解决方案1】:

天真的方法会给你 theta(n^3) 时间——你检查过something simpler吗?

如果做不到这一点,你看过thesesimilar问题吗?

【讨论】:

  • 我必须递归地写。我看过那个三重循环,我不允许使用它。我也看到了其他两个问题,但没有完全回答。用你链接到“这些”这个词的书中的文字显示图片的那个是我需要写的相同方法和同一本书。但是回答的人基本上又写了伪代码,我理解。我现在已经尝试将它写入代码,这就是我在上面发布的内容。 ://
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
相关资源
最近更新 更多