码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-22 13:18:24      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   query   mat   ogr   stat   entry   blog   pre   rect   

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 }

 

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

标签:style   query   mat   ogr   stat   entry   blog   pre   rect   

原文地址:http://www.cnblogs.com/lz87/p/7292280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!