Two Dimensional Difference Array | C # program to implement the above approach ; Function to initialize the difference array ; Function to add k to the specified submatrix ( r1 , c1 ) to ( r2 , c2 ) ; Function to print the modified array ; Function to perform the given queries ; Difference array ; Function to initialize the difference array ; Count of queries ; Perform Queries ; Driver Code ; Given Matrix ; Given Queries
using System ; using System . Collections . Generic ; class GFG { static int N = 3 ; static int M = 3 ; static void intializeDiff ( int [ , ] D , int [ , ] A ) { for ( int i = 0 ; i < N ; i ++ ) { D [ i , 0 ] = A [ i , 0 ] ; D [ i , M ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) D [ i , j ] = A [ i , j ] - A [ i , j - 1 ] ; } } static void update ( int [ , ] D , int k , int r1 , int c1 , int r2 , int c2 ) { for ( int i = r1 ; i <= r2 ; i ++ ) { D [ i , c1 ] += k ; D [ i , c2 + 1 ] -= k ; } } static void printArray ( int [ , ] A , int [ , ] D ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( j == 0 ) A [ i , j ] = D [ i , j ] ; else A [ i , j ] = D [ i , j ] + A [ i , j - 1 ] ; Console . Write ( A [ i , j ] + " ▁ " ) ; } Console . WriteLine ( ) ; } } static void performQueries ( int [ , ] A , List < List < int > > Queries ) { int [ , ] D = new int [ N , M + 1 ] ; intializeDiff ( D , A ) ; int Q = Queries . Count ; for ( int i = 0 ; i < Q ; i ++ ) { update ( D , Queries [ i ] [ 0 ] , Queries [ i ] [ 1 ] , Queries [ i ] [ 2 ] , Queries [ i ] [ 3 ] , Queries [ i ] [ 4 ] ) ; } printArray ( A , D ) ; } static void Main ( ) { int [ , ] A = { { 1 , 2 , 3 } , { 1 , 1 , 0 } , { 4 , - 2 , 2 } } ; List < List < int > > Queries = new List < List < int > > ( ) ; Queries . Add ( new List < int > { 2 , 0 , 0 , 1 , 1 } ) ; Queries . Add ( new List < int > { - 1 , 1 , 0 , 2 , 2 } ) ; performQueries ( A , Queries ) ; } }