Given a 2-D matrix mat[][] of size N * N, initially all the elements of the matrix are 0. A number of queries(M ranges) need to be performed on the matrix where each query consists of four integers X1, Y1, X2 and Y2, the task is to add 1 to all the cells between mat[X1][Y1] and mat[X2][Y2] (including both) and print the contents of the updated matrix in the end.
Examples:Â
Â
Input: N = 2, q[][] = { { 0, 0, 1, 1 }, { 0, 0, 0, 1 } }Â
Output:Â
2 2Â
1 1Â
After 1st query: mat[][] = { {1, 1}, {1, 1} }Â
After 2nd query: mat[][] = { {2, 2}, {1, 1} }Input: N = 5, q[][] = { { 0, 0, 1, 2 }, { 1, 2, 3, 4 }, { 1, 4, 3, 4 } }Â
Output:Â
1 1 1 1 1Â
1 1 2 1 2Â
2 2 2 2 2Â
2 2 2 2 2Â
0 0 0 0 0Â
Approach: For each query (X1, Y1) represents the top left cell of the sub-matrix and (X2, Y2) represents the bottom right cell of the sub-matrix. For each top left cell add 1 to the top left element and subtract 1 from the element next to bottom right cell (if any).Â
Then maintain a running sum of all the elements from the original (now modified) matrix and at every addition, the current sum is the element (updated) at the current position.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std;Â
// Function to update and print the // matrix after performing queriesvoid 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];Â
        // Add 1 to the first element of         // the sub-matrix        mat[X1][Y1]++;Â
        // If there is an element after the         // last element of the sub-matrix         // then decrement it by 1        if (Y2 + 1 < n)            mat[X2][Y2 + 1]--;        else if (X2 + 1 < n)            mat[X2 + 1][0]--;    }Â
    // Calculate the running sum    int sum = 0;    for (i = 0; i < n; i++)    {        for (j = 0; j < n; j++)         {            sum += mat[i][j];Â
            // Print the updated element            cout << sum << " ";        }Â
        // Next line        cout << endl;    }}Â
// Driver codeint main(){Â
    // Size of the matrix    int n = 5;     Â
    // Queries    int q[3][4] = {{ 0, 0, 1, 2 },                   { 1, 2, 3, 4 },                   { 1, 4, 3, 4 }};Â
    updateMatrix(n, q);    return 0;}Â
// This code is contributed by chandan_jnu |
Java
// Java implementation of the approachpublic class GFG {Â
    // Function to update and print the matrix    // after performing queries    static void updateMatrix(int n, int q[][], int mat[][])    {        int i, j;        for (i = 0; i < q.length; i++) {            int X1 = q[i][0];            int Y1 = q[i][1];            int X2 = q[i][2];            int Y2 = q[i][3];Â
            // Add 1 to the first element of the sub-matrix            mat[X1][Y1]++;Â
            // If there is an element after the last element            // of the sub-matrix then decrement it by 1            if (Y2 + 1 < n)                mat[X2][Y2 + 1]--;            else if (X2 + 1 < n)                mat[X2 + 1][0]--;        }Â
        // Calculate the running sum        int sum = 0;        for (i = 0; i < n; i++) {            for (j = 0; j < n; j++) {                sum += mat[i][j];Â
                // Print the updated element                System.out.print(sum + " ");            }Â
            // Next line            System.out.println();        }    }Â
    // Driver code    public static void main(String[] args)    {Â
        // Size of the matrix        int n = 5;        int mat[][] = new int[n][n];Â
        // Queries        int q[][] = { { 0, 0, 1, 2 },                      { 1, 2, 3, 4 },                      { 1, 4, 3, 4 } };Â
        updateMatrix(n, q, mat);    }} |
Python3
# Python 3 implementation of the approachÂ
# Function to update and print the matrix# after performing queriesdef updateMatrix(n, q, mat):Â Â Â Â Â Â Â Â Â Â Â Â Â for i in range(0, len(q)):Â Â Â Â Â Â Â Â Â Â Â Â X1 = q[i][0];Â Â Â Â Â Â Â Â Â Â Â Â Y1 = q[i][1];Â Â Â Â Â Â Â Â Â Â Â Â X2 = q[i][2];Â Â Â Â Â Â Â Â Â Â Â Â Y2 = q[i][3];Â
            # Add 1 to the first element of            # the sub-matrix            mat[X1][Y1] = mat[X1][Y1] + 1;Â
            # If there is an element after the             # last element of the sub-matrix            # then decrement it by 1            if (Y2 + 1 < n):                mat[X2][Y2 + 1] = mat[X2][Y2 + 1] - 1;            elif (X2 + 1 < n):                mat[X2 + 1][0] = mat[X2 + 1][0] - 1;Â
    # Calculate the running sum    sum = 0;    for i in range(0, n):        for j in range(0, n):             sum =sum + mat[i][j];Â
            # Print the updated element            print(sum, end = ' ');                     # Next line        print(" ");         # Driver codeÂ
# Size of the matrixn = 5;mat = [[0 for i in range(n)] Â Â Â Â Â Â Â Â Â Â for i in range(n)];Â
# Queriesq = [[ 0, 0, 1, 2 ],     [ 1, 2, 3, 4 ],     [ 1, 4, 3, 4 ]];Â
updateMatrix(n, q, mat);Â Â Â Â Â # This code is contributed # by Shivi_Aggarwal |
C#
// C# implementation of the above approach Â
using System;Â
public class GFG { Â
    // Function to update and print the matrix     // after performing queries     static void updateMatrix(int n, int [,]q, int [,]mat)     {         int i, j;         for (i = 0; i < q.GetLength(0); i++) {             int X1 = q[i,0];             int Y1 = q[i,1];             int X2 = q[i,2];             int Y2 = q[i,3]; Â
            // Add 1 to the first element of the sub-matrix             mat[X1,Y1]++; Â
            // If there is an element after the last element             // of the sub-matrix then decrement it by 1             if (Y2 + 1 < n)                 mat[X2,Y2 + 1]--;             else if (X2 + 1 < n)                 mat[X2 + 1,0]--;         } Â
        // Calculate the running sum         int sum = 0;         for (i = 0; i < n; i++) {             for (j = 0; j < n; j++) {                 sum += mat[i,j]; Â
                // Print the updated element                 Console.Write(sum + " ");             } Â
            // Next line             Console.WriteLine();         }     } Â
    // Driver code     public static void Main()     { Â
        // Size of the matrix         int n = 5;         int [,]mat = new int[n,n]; Â
        // Queries         int [,]q = { { 0, 0, 1, 2 },                     { 1, 2, 3, 4 },                     { 1, 4, 3, 4 } }; Â
        updateMatrix(n, q, mat);     }     // This code is contributed by Ryuga} |
PHP
<?php// PHP implementation of the approachÂ
// Function to update and print the // matrix after performing queriesfunction updateMatrix($n, $q, $mat){Â Â Â Â for ($i = 0; $i < sizeof($q); $i++) Â Â Â Â {Â Â Â Â Â Â Â Â $X1 = $q[$i][0];Â Â Â Â Â Â Â Â $Y1 = $q[$i][1];Â Â Â Â Â Â Â Â $X2 = $q[$i][2];Â Â Â Â Â Â Â Â $Y2 = $q[$i][3];Â
        // Add 1 to the first element of         // the sub-matrix        $mat[$X1][$Y1]++;Â
        // If there is an element after the last         // element of the sub-matrix then decrement         // it by 1        if ($Y2 + 1 < $n)            $mat[$X2][$Y2 + 1]--;        else if ($X2 + 1 < $n)            $mat[$X2 + 1][0]--;    }Â
    // Calculate the running sum    $sum = 0;    for ($i = 0; $i < $n; $i++)     {        for ($j = 0; $j < $n; $j++)         {            $sum += $mat[$i][$j];Â
            // Print the updated element            echo($sum . " ");        }Â
        // Next line        echo("\n");    }}Â
// Driver codeÂ
// Size of the matrix$n = 5;$mat = array_fill(0, $n,       array_fill(0, $n, 0));Â
// Queries$q = array(array( 0, 0, 1, 2 ),           array( 1, 2, 3, 4 ),           array( 1, 4, 3, 4 ));Â
updateMatrix($n, $q, $mat);Â
// This code is contributed by chandan_jnu?> |
Javascript
<script>    // Javascript implementation of the approach         // Function to update and print the matrix    // after performing queries    function updateMatrix(n, q, mat)    {        let i, j;        for (i = 0; i < q.length; i++) {            let X1 = q[i][0];            let Y1 = q[i][1];            let X2 = q[i][2];            let Y2 = q[i][3];               // Add 1 to the first element of the sub-matrix            mat[X1][Y1]++;               // If there is an element after the last element            // of the sub-matrix then decrement it by 1            if (Y2 + 1 < n)                mat[X2][Y2 + 1]--;            else if (X2 + 1 < n)                mat[X2 + 1][0]--;        }           // Calculate the running sum        let sum = 0;        for (i = 0; i < n; i++) {            for (j = 0; j < n; j++) {                sum += mat[i][j];                   // Print the updated element                document.write(sum + " ");            }               // Next line            document.write("</br>");        }    }         // Size of the matrix    let n = 5;    let mat = new Array(n);    for(let i = 0; i < n; i++)    {        mat[i] = new Array(n);        for(let j = 0; j < n; j++)        {            mat[i][j] = 0;        }    }Â
    // Queries    let q = [ [ 0, 0, 1, 2 ],              [ 1, 2, 3, 4 ],              [ 1, 4, 3, 4 ] ];Â
    updateMatrix(n, q, mat);         // This code is contributed by divyeshrabadiya07.</script> |
1 1 1 1 1 1 1 2 1 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0
Complexity Analysis:
- Time Complexity: O(n2)
- Auxiliary Space: O(n2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More here on that Topic: geeksforgeeks.org/print-matrix-after-applying-increment-operations-in-m-ranges/ […]