什么是Submatrix Sum Queries程序?它的用途和概念是什么?

时间:2016-08-20 18:41:52

标签: java algorithm matrix data-structures dynamic-programming

我在geeksforgeeks找到了这个问题。在亚马逊的采访过程中被问到了这个问题。以下是链接: http://www.geeksforgeeks.org/submatrix-sum-queries/

如果有人知道这个问题,请向我解释。

2 个答案:

答案 0 :(得分:0)

关于如何解决问题的解释在您提供的链接背后非常详细。

答案 1 :(得分:0)

public static int sumMatSumInConstantTime(int[][] mat, int is, int js, int ie, int je) {

    processMatForConstantTimeSum(mat);

    int sum = mat[ie][je];
    int count = 0;
    if (is - 1 >= 0) {
        sum -= mat[is - 1][je];
        count++;
    }
    if (js - 1 >= 0) {
        sum -= mat[ie][js - 1];
        count++;
    }
    /**
     * since one rectangle is deducted twice
     */
    if (count == 2)
        sum += mat[is - 1][js - 1];

    return sum;
}

private static void processMatForConstantTimeSum(int[][] mat) {

    int r = mat.length;
    int c = mat[0].length;

    /**
     * sum rows
     */
    for (int i = 0; i < r; i++) {
        int sum = 0;
        for (int j = 0; j < c; j++) {
            sum += mat[i][j];
            mat[i][j] = sum;
        }
    }
    /**
     * sum cols
     */
    for (int i = 0; i < c; i++) {
        int sum = 0;
        for (int j = 0; j < r; j++) {
            sum += mat[j][i];
            mat[j][i] = sum;
        }
    }
}