Print matrix after applying increment operations in M ranges | C ++ implementation of the approach ; Function to update and print the matrix after performing queries ; Add 1 to the first element of the sub - matrix ; If there is an element after the last element of the sub - matrix then decrement it by 1 ; Calculate the running sum ; Print the updated element ; Next line ; Driver code ; Size of the matrix ; Queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateMatrix ( int n , int q [ 3 ] [ 4 ] ) { int i , j ; int mat [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) mat [ i ] [ j ] = 0 ; for ( i = 0 ; i < 3 ; i ++ ) { int X1 = q [ i ] [ 0 ] ; int Y1 = q [ i ] [ 1 ] ; int X2 = q [ i ] [ 2 ] ; int Y2 = q [ i ] [ 3 ] ; mat [ X1 ] [ Y1 ] ++ ; if ( Y2 + 1 < n ) mat [ X2 ] [ Y2 + 1 ] -- ; else if ( X2 + 1 < n ) mat [ X2 + 1 ] [ 0 ] -- ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { sum += mat [ i ] [ j ] ; cout << sum << " ▁ " ; } cout << endl ; } } int main ( ) { int n = 5 ; int q [ 3 ] [ 4 ] = { { 0 , 0 , 1 , 2 } , { 1 , 2 , 3 , 4 } , { 1 , 4 , 3 , 4 } } ; updateMatrix ( n , q ) ; return 0 ; }