[Coding Made Simple] Sum Query in 2D Immutable Array

Given a 2D immutable array,  Write an efficient program to support any given sub-rectangle sum query in this 2D matrix.

 

A simple solution is to add each entry inside the sub-rectangle. The runtime is O(n * m).

The problem of this solution is that for a given 2D matrix, we always start from scratch to compute the sum of a sub-rectangle.

 

Dynamic programming should be used to optimize the runtime.

State: T[i][j]: the sum of sub rectangle with top left corner (0, 0) and bottom right corner (i - 1, j - 1).

Function: T[i][j] = T[i - 1][j] + T[i][j - 1] + matrix[i - 1][j - 1] - T[i - 1][j - 1].

Initialization: T[0][j] = T[i][0] = 0; 

Answer:  given top left corner(x1, y1) and bottom right corner(x2, y2), 

    Sum of sub rectangle(x1, y1, x2, y2) is T[x2 + 1][y2 + 1] - T[x1][y2 + 1] - T[x2 + 1][y1] + T[x1][y1].

 

 1 public class SumQuery {
 2     private int[][] T;
 3     public SumQuery(int[][] matrix) {
 4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
 5             T = null;
 6         }
 7         T = new int[matrix.length + 1][matrix[0].length + 1];
 8         for(int i = 0; i < T.length; i++) {
 9             T[i][0] = 0;
10         }
11         for(int j = 0; j < T[0].length; j++) {
12             T[0][j] = 0;
13         }
14         for(int i = 1; i < T.length; i++) {
15             for(int j = 1; j < T[0].length; j++) {
16                 T[i][j] = T[i - 1][j] + T[i][j - 1] + matrix[i - 1][j - 1] - T[i - 1][j - 1];
17             }
18         }
19     }
20     public int querySubRectangleSum(int x1, int y1, int x2, int y2) {
21         x1++; y1++; x2++; y2++;
22         return T[x2][y2] - T[x1 - 1][y2] - T[x2][y1 - 1] + T[x1 - 1][y1 - 1];
23     }
24 }

 

posted @ 2017-08-22 12:08  Review->Improve  阅读(171)  评论(0编辑  收藏  举报