Sunday, July 19, 2020

Leetcode discuss: 304. Range Sum Query 2D - Immutable

Here is the link. 

C# preprocess matrix to calculate left top corner area

July 19, 2020

Introduction
In order to get O(1) to answer the query given start left top corner and bottom right corner, it is a good idea to preprocess the left top corner area for any position in the matrix.

My practice
It took me over 20 minutes and reviewed the code since one failed test case. My first submission failed since the cross area is related to (row1 - 1, col1 - 1), not (row1, col1).

public class NumMatrix {
    private int[][] rectangle; // from (0,0) to (i, j) rectangle sum
    private int rows, columns;
    public NumMatrix(int[][] matrix) {
        if(matrix == null || matrix.Length == 0 || matrix[0].Length == 0)
            return;
        
        rows = matrix.Length;
        columns = matrix[0].Length; 
        
        rectangle = new int[rows][];
        for(int i = 0; i < rows; i++)
        {
            rectangle[i] = new int[columns];
        }
        
        for(int row = 0; row < rows; row++)
        {
            for(int col = 0; col < columns; col++)
            {
                var left = col > 0? rectangle[row][col - 1] : 0;
                var upper = row > 0? rectangle[row - 1][col] : 0;
                var cross = (row > 0 && col > 0)? rectangle[row -1 ][col - 1] : 0;
                rectangle[row][col] = matrix[row][col] + left + upper - cross;
            }
        }
    }
    
    public int SumRegion(int row1, int col1, int row2, int col2) {
      if(row1 < 0 || row1 >= rows || 
         row2 < 0 || row2 >= rows || 
         row1 > row2 ||
         col1 < 0 || col1 >= columns ||
         col2 < 0 || col2 >= columns ||
         col1 > col2)
          return -1; 
        //            whole - left - up + cross              
        var area = rectangle[row2][col2]; // whole
        area -= col1 == 0? 0: rectangle[row2][col1 - 1]; // left
        area -= row1 == 0? 0: rectangle[row1 - 1][col2]; // up
        area += col1 == 0 || row1 == 0? 0: rectangle[row1-1][col1-1]; // cross
        
      return   area;         
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * int param_1 = obj.SumRegion(row1,col1,row2,col2);
 */


No comments:

Post a Comment