Two Dimensional Difference Array | Java 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
import java . util . * ; 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 ] ; System . out . print ( A [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } static void performQueries ( int A [ ] [ ] , Vector < Vector < Integer > > Queries ) { int D [ ] [ ] = new int [ N ] [ M + 1 ] ; intializeDiff ( D , A ) ; int Q = Queries . size ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { update ( D , Queries . get ( i ) . get ( 0 ) , Queries . get ( i ) . get ( 1 ) , Queries . get ( i ) . get ( 2 ) , Queries . get ( i ) . get ( 3 ) , Queries . get ( i ) . get ( 4 ) ) ; } printArray ( A , D ) ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 2 , 3 } , { 1 , 1 , 0 } , { 4 , - 2 , 2 } } ; Vector < Vector < Integer > > Queries = new Vector < Vector < Integer > > ( ) ; Vector < Integer > list1 = new Vector < Integer > ( ) ; list1 . add ( 2 ) ; list1 . add ( 0 ) ; list1 . add ( 0 ) ; list1 . add ( 1 ) ; list1 . add ( 1 ) ; Vector < Integer > list2 = new Vector < Integer > ( ) ; list2 . add ( - 1 ) ; list2 . add ( 1 ) ; list2 . add ( 0 ) ; list2 . add ( 2 ) ; list2 . add ( 2 ) ; Queries . add ( list1 ) ; Queries . add ( list2 ) ; performQueries ( A , Queries ) ; } }