@@ -0,0 +1,1748 @@
+package miscellaneous.design.lc304_rangesumquery2dimmutable;%0A%0A/**%0A */%0Apublic class NumMatrix %7B%0A%0A    public static void main(String%5B%5D args) %7B%0A        NumMatrix matrix = new NumMatrix(%0A                new int%5B%5D%5B%5D%7B%0A                        %7B3, 0, 1, 4, 2%7D,%0A                        %7B5, 6, 3, 2, 1%7D,%0A                        %7B1, 2, 0, 1, 5%7D,%0A                        %7B4, 1, 0, 1, 7%7D,%0A                        %7B1, 0, 3, 0, 5%7D%0A                %7D%0A        );%0A        System.out.println(matrix.sumRegion(2, 1, 4, 3));%0A        System.out.println(matrix.sumRegion(1, 1, 2, 2));%0A        System.out.println(matrix.sumRegion(1, 2, 2, 4));%0A%0A        System.out.println(matrix.sumRegion(1, 0, 2, 4));%0A        System.out.println(matrix.sumRegion(1, 1, 1, 1));%0A    %7D%0A%0A    // Similar to intermediate result table%0A    private int%5B%5D%5B%5D cacheSum;%0A%0A    public NumMatrix(int%5B%5D%5B%5D matrix) %7B%0A        if (matrix.length == 0 %7C%7C matrix%5B0%5D.length == 0) %7B%0A            return;%0A        %7D%0A        this.cacheSum = new int%5Bmatrix.length%5D%5Bmatrix%5B0%5D.length%5D;%0A        for (int i = 0; i %3C matrix.length; i++) %7B%0A            int rowSum = 0;%0A            for (int j = 0; j %3C matrix%5Bi%5D.length; j++) %7B%0A                rowSum += matrix%5Bi%5D%5Bj%5D;%0A                cacheSum%5Bi%5D%5Bj%5D = rowSum;%0A            %7D%0A        %7D%0A    %7D%0A%0A    public int sumRegion(int row1, int col1, int row2, int col2) %7B%0A        if (cacheSum == null) %7B%0A            return 0;%0A        %7D%0A        int rangeSum = 0;%0A        if (col1 == 0) %7B%0A            for (int i = row1; i %3C= row2; i++) %7B%0A                rangeSum += cacheSum%5Bi%5D%5Bcol2%5D;%0A            %7D%0A        %7D else %7B%0A            for (int i = row1; i %3C= row2; i++) %7B%0A                rangeSum += (cacheSum%5Bi%5D%5Bcol2%5D - cacheSum%5Bi%5D%5Bcol1 - 1%5D);%0A            %7D%0A        %7D%0A        return rangeSum;%0A    %7D%0A%0A%7D%0A

leetcode-304 range sum query 2D immutable