在具有负整数的矩阵中找到某些矩形SUM(JAVA)

时间:2016-11-28 10:48:41

标签: java matrix multidimensional-array sum rectangles

我要找到一个矩形的sumin矩阵。我找到了this 但这似乎不适用于矩阵中的负整数。我怎么能改变代码所以它可以用负整数?我现在没希望了。 矩阵在代码中

output should be: desired number @ (top,left) - (right,bottom) 12 @ (0,3) - (2,4) 12 @ (0,4) - (4,5) 12 @ (2,2) - (2,3) 12 @ (4,0) - (4,1) my output: 12 @ (0,4) - (1,5) 12 @ (2,2) - (3,3) 12 @ (3,0) - (4,2) 12 @ (4,0) - (5,4)

我使用的代码:

public static void main(String[] args) {
        int[][] A = {
            {-13, 9 ,-16 , 14,   3},
            {11,  7 , -5 , 14,   9},
            {-2,  -5,  9 , -9 , -4},
            {11,  13,  3 ,  8 ,-16},
            {-1, -15,  1 , -4,   2},
            {3 ,  7,  -8 ,  0,  27},
    };
    int target = 12;

    for (int i = 1; i < A.length; i++){
        for (int j = 0; j < A[i].length; j++){
            A[i][j] += A[i - 1][j];
            System.out.print(A[i][j] + " ");
        }System.out.println("");
     }

    for (int i1 = 0; i1 < A.length; i1++) {
        for (int i2 = i1 + 1; i2 < A.length; i2++) {
            int j1=0, j2=0, s=0;

            while(j2<A[i1].length) {
                while(s<target && j2<A[i1].length) {
                    s += A[i2][j2] - (i1 > 0 ? A[i1-1][j2] : 0);
                    j2++;
                    if (s==target)
                        System.out.println(String.format("Found between (%d,%d) and (%d,%d)", i1, j1, i2, j2-1));
                }
                while(s>=target) {
                    s -= A[i2][j1] - (i1 > 0 ? A[i1-1][j1] : 0);
                    j1++;
                    if (s==target)
                        System.out.println(String.format("Found between (%d,%d) and (%d,%d)", i1, j1, i2, j2));
                }
            }
        }
    }
    }

0 个答案:

没有答案