有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

nxn矩阵的c#最大子矩阵和

我试图从给定的nxn矩阵得到最大子矩阵和。据我所知,算法的复杂度为n^3(kadane)。我试图使用我在stackoverflow(由Anders Gustafsson用C#in these post编写)上找到的代码在java中实现它,但它似乎并不总是有效

我的代码是:

public static void maxSubMatrix(int matrix[][]) {
    // O(n^3) Max Sum Submatrix

    int row = matrix.length;
    int col = matrix[0].length; // Get the col-length by taking the length of 
                                // row 0 (in programm the matrices will be n x n)

    // Initialise maxSum
    int maxSum = 0;

    // Set left column
    for (int left=0; left<col; left++) {

        // Initialise array
        int tempArray[] = new int[row];

        // Set right column by left column (outer loop)
        for (int right=left; right<col; right++){

            // Calculate sum between current left-right for every row 'i'
            for (int i=0; i<row; i++)
                tempArray[i] = matrix[i][right];
            // ----

            // Find maximum sum in tempArray[]
            int sum = maxSubArray(tempArray);

            // Compare sum with maxSum so far, and update it if necessary
            if (sum > maxSum) maxSum = sum;
        }
    }
    System.out.println(maxSum);
}
// ==========================

public static int maxSubArray(int array[]){
    // Kadane O(n) Max Sum Subarray
    int maxSum = 0;
    int tempSum = 0;

    for (int i=0; i<array.length; i++){
        int b = array[i];
        if (tempSum + b > 0) tempSum += b;
        else tempSum = 0;
        maxSum = Math.max(maxSum, tempSum);
    }
    return maxSum;
}

我举了三个例子:

矩阵1
-2-3
-1-4
输出为0(空的0x0矩阵也是一个解决方案)

矩阵2
2-1
-2-1
输出为2

矩阵3
-13
3-1
输出是3,但应该是4

也许有人能看到错误。我也愿意接受全新的想法来实施它


共 (1) 个答案

  1. # 1 楼答案

    您刚刚忘记将下一个rigth元素添加到临时数组:

    (int i=0; i<row; i++)
                tempArray[i] += matrix[i][right];
    

    现在一切都好了!;)

    格里茨