Final Matrix after incrementing submatrices by K in range given by Q queries | C # program for the above approach ; Query data type ; Function to update the given query ; Update top cell ; Update bottom left cell ; Update bottom right cell ; Update top right cell ; Function that updates the matrix [ , ] mat by adding elements of aux [ , ] ; Compute the prefix sum of all columns ; Compute the prefix sum of all rows ; Get the readonly matrix by adding mat and aux matrix at each cell ; Function that prints matrix [ ] mat ; Traverse each row ; Traverse each columns ; Function that performs each query in the given matrix and print the updated matrix after each operation performed ; Initialize all elements to 0 ; Update auxiliary matrix by traversing each query ; Update Query ; Compute the readonly answer ; Print the updated matrix ; Driver Code ; Given Matrix ; Given Queries ; Function call
using System ; class GFG { static readonly int N = 3 ; static readonly int M = 4 ; class query { public int x1 , x2 , y1 , y2 , K ; public query ( int x1 , int x2 , int y1 , int y2 , int k ) { this . x1 = x1 ; this . x2 = x2 ; this . y1 = y1 ; this . y2 = y2 ; K = k ; } } ; static void updateQuery ( int from_x , int from_y , int to_x , int to_y , int k , int [ , ] aux ) { aux [ from_x , from_y ] += k ; if ( to_x + 1 < N ) aux [ to_x + 1 , from_y ] -= k ; if ( to_x + 1 < N && to_y + 1 < M ) aux [ to_x + 1 , to_y + 1 ] += k ; if ( to_y + 1 < M ) aux [ from_x , to_y + 1 ] -= k ; } static void updateMatrix ( int [ , ] mat , int [ , ] aux ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { aux [ i , j ] += aux [ i , j - 1 ] ; } } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 1 ; j < N ; j ++ ) { aux [ j , i ] += aux [ j - 1 , i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { mat [ i , j ] += aux [ i , j ] ; } } } static void printMatrix ( int [ , ] mat ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { Console . Write ( mat [ i , j ] + " ▁ " ) ; } Console . Write ( " STRNEWLINE " ) ; } } static void matrixQuery ( int [ , ] mat , int Q , query [ ] q ) { int [ , ] aux = new int [ N , M ] ; for ( int i = 0 ; i < Q ; i ++ ) { updateQuery ( q [ i ] . x1 , q [ i ] . x2 , q [ i ] . y1 , q [ i ] . y2 , q [ i ] . K , aux ) ; } updateMatrix ( mat , aux ) ; printMatrix ( mat ) ; } public static void Main ( String [ ] args ) { int [ , ] mat = { { 1 , 0 , 1 , 2 } , { 0 , 2 , 4 , 1 } , { 1 , 2 , 1 , 0 } } ; int Q = 1 ; query [ ] q = { new query ( 0 , 0 , 1 , 1 , 2 ) } ; matrixQuery ( mat , Q , q ) ; } }