Open In App

Count of empty cells in given square Matrix after updating the rows and columns for Q queries

Last Updated : 10 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary matrix of size NxN which is initially filled with 0’s and Q queries such that:

  • Each query is of type (r, c) where r and c denotes the row number and column number respectively.
  • Change all the 0’s of rth row and cth column to 1.

The task is to find the count of 0’s after performing each query in the given matrix.

 Examples:

Input: N = 3, Q = 3, queries = {{2, 2}, {2, 3}, {3, 2}}
Output: 4 2 1
Explanation: After 1st Operation, all the 2nd row and all the 2nd column will be filled by 1. So remaining cell with value 0 will be 4.
After 2nd Operation, all the 2nd row and all the 3rd column will be filled by 1. So remaining cell with value 0 will be 2. 
After 3rd Operation cells having value 0 will be 1. 

Input: N = 4, Q = 3, queries = {{3, 1}, {3, 3}, {4, 2}}
Output: 9 6 3 
Explanation: After 1st operation, all the 3rd row and all the 1st column will be filled by 1. So, remaining cell with value 0 will be 9.
After 2nd Operation, all the 3rd row and all the 3rd column will be filled by 1. So, remaining cell with value 0 will be 6.
After 3rd Operation cells having value 0 will be 3.

 

Naive Approach: The basic approach to solve this problem is to update the elements of the matrix for elements in the row and column mentioned for a query and then traverse the whole matrix to find the count of remaining zeroes. This process will be repeated for all the Q queries.

Time  Complexity: O(Q*(N+N2)) = O(Q*(N2))
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by removing the need to traverse the matrix for Q queries with the help of hashing.

  • Create a hash array to store the scanned row and column.
  • Declare variable r and c to store count of 0 present in row and column and declare ans and store NxN .
  • Now start traversing the given array, and in each iteration:
    • Check whether current row and column already exists or not in hash array.
    • If current row is not present, subtract r from ans and decrement value of c by 1.
    • If current column is not present, subtract given c from ans and decrement value of r by 1.
    • Push ans in vector.

Illustration: 

Consider the matrix:

N=3

0 0 0

0 0 0

0 0 0

Initially ans=n*n=9, r=3(Number of zeros in row) and c=3(Number of zeros in column)

Traverse through each given query

for e.g queries = {{2, 2}, {2, 3}, {3, 2}}

Select 1st query row=2 and column=2, check whether this row or column is already converted to one or not using hashmap.

Here row=2 is not visited, so convert all the zeros present in that row to one i.e ans-=r, due to this number of zeros in each column decremented by 1 i.e c–.

0 0 0

1 1 1

0 0 0

Now ans=9-3=6, r=3(Number of zeros in row) and c=2(Number of zeros in column)

Here col=2 is not visited in 1st query, so convert all the zeros present in that column to one i.e ans-=c, due to this number of zeros in each row decremented by 1 i.e r–.

0 1 0

1 1 1

0 1 0

Now ans=6-2=4, r=2(Number of zeros in row) and c=2(Number of zeros in column)

So after execution of 1st query number of remaining zeros is 4.

Select 2nd query row=2 and column=3, check whether this row or column is already converted to one or not using hashmap.

Here row=2 is already visited, So just continue.

Here col=3 is not visited in 1st query, so convert all the zeros present in that column to one i.e ans-=c, due to this number of zeros in each row decremented by 1 i.e r–.

0 1 1

1 1 1

0 1 1

Now ans=4-2=2, r=1(Number of zeros in row) and c=2(Number of zeros in column)

So after execution of 2nd query number of remaining zeros is 2.

Repeat the process for all query

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach.
#include <bits/stdc++.h>
using namespace std;
 
vector<long long int> countZero(
    int n, int k,
    vector<vector<int> >& arr)
{
    long long int ans = n, r = n, c = n;
    // for declaring n*n matrix
    ans *= ans;
    vector<bool> row(n + 1, true), col(n + 1, true);
    vector<long long int> v;
    for (int i = 0; i < k; i++) {
 
        // If current row is not present,
        // subtract r from ans
        if (row[arr[i][0]]) {
            ans -= r;
            c--;
            row[arr[i][0]] = false;
        }
 
        // If current column is not present,
        // subtract c from ans and
        // decrement value of r by 1.
        if (col[arr[i][1]]) {
            ans -= c;
            r--;
            col[arr[i][1]] = false;
        }
        v.push_back(ans);
    }
    return v;
}
 
// Driver code
int main()
{
    int N = 3, Q = 3;
    vector<vector<int> > arr
        = { { 2, 2 }, { 2, 3 }, { 3, 2 } };
    vector<long long int> ans = countZero(N, Q, arr);
 
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    cout << endl;
 
    return 0;
}


Java




// Java code to implement the above approach.
import java.util.*;
class GFG{
 
  static Vector<Integer> countZero(
    int n, int k,
    int [][]  arr)
  {
    int ans = n, r = n, c = n;
 
    // for declaring n*n matrix
    ans *= ans;
    boolean []row = new boolean[n+1];
    Arrays.fill(row, true);
    boolean []col = new boolean[n+1];
    Arrays.fill(col, true);
    Vector<Integer> v = new Vector<Integer>();
    for (int i = 0; i < k; i++) {
 
      // If current row is not present,
      // subtract r from ans
      if (row[arr[i][0]]) {
        ans -= r;
        c--;
        row[arr[i][0]] = false;
      }
 
      // If current column is not present,
      // subtract c from ans and
      // decrement value of r by 1.
      if (col[arr[i][1]]) {
        ans -= c;
        r--;
        col[arr[i][1]] = false;
      }
      v.add(ans);
    }
    return v;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 3, Q = 3;
    int [][] arr
      = { { 2, 2 }, { 2, 3 }, { 3, 2 } };
    Vector<Integer> ans = countZero(N, Q, arr);
 
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i)+ " ");
    }
    System.out.println();
 
  }
}
 
// This code is contributed by 29AjayKumar


Python3




# Python program for the above approach
def countZero(n, k, arr) :
     
    ans = n
    r = n
    c = n
     
    # for declaring n*n matrix
    ans *= ans
    row = [True] * (n + 1)
    col = [True] * (n + 1)
    v= [[]]
    for i in range(k):
 
        # If current row is not present,
        # subtract r from ans
        if (row[arr[i][0]]) :
            ans -= r
            c -= 1
            row[arr[i][0]] = False
         
 
        # If current column is not present,
        # subtract c from ans and
        # decrement value of r by 1.
        if (col[arr[i][1]]) :
            ans -= c
            r -= 1
            col[arr[i][1]] = False
         
        v.append(ans)
     
    return v
 
# Driver code
N = 3
Q = 3
arr = [[ 2, 2 ], [ 2, 3 ], [ 3, 2 ]]
ans = countZero(N, Q, arr)
 
for i in range(1, len(ans)):
   print(ans[i], end = " ")
     
# This code is contributed by code_hunt.


C#




// C# code to implement the above approach.
using System;
using System.Collections;
 
class GFG {
 
  static ArrayList countZero(int n, int k, int[, ] arr)
  {
    int ans = n, r = n, c = n;
 
    // for declaring n*n matrix
    ans *= ans;
    ArrayList row = new ArrayList(n + 1);
    ArrayList col = new ArrayList(n + 1);
 
    for (int i = 0; i < n + 1; i++) {
      row.Add(1);
      col.Add(1);
    }
 
    ArrayList v = new ArrayList();
    for (int i = 0; i < k; i++) {
 
      // If current row is not present,
      // subtract r from ans
      if ((int)row[arr[i, 0]] == 1) {
        ans -= r;
        c--;
        row[arr[i, 0]] = 0;
      }
 
      // If current column is not present,
      // subtract c from ans and
      // decrement value of r by 1.
      if ((int)col[arr[i, 1]] == 1) {
        ans -= c;
        r--;
        col[arr[i, 1]] = 0;
      }
      v.Add(ans);
    }
    return v;
  }
 
  // Driver code
  public static void Main()
  {
    int N = 3, Q = 3;
    int[, ] arr = { { 2, 2 }, { 2, 3 }, { 3, 2 } };
 
    ArrayList ans = countZero(N, Q, arr);
 
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i] + " ");
    }
    Console.WriteLine();
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
       function countZero(n, k, arr)
       {
           let ans = n, r = n, c = n;
         
            // for declaring n*n matrix
           ans *= ans;
           let row = new Array(n + 1).fill(true), col = new Array(n + 1).fill(true);
           let v = [];
           for (let i = 0; i < k; i++) {
 
               // If current row is not present,
               // subtract r from ans
               if (row[arr[i][0]]) {
                   ans -= r;
                   c--;
                   row[arr[i][0]] = false;
               }
 
               // If current column is not present,
               // subtract c from ans and
               // decrement value of r by 1.
               if (col[arr[i][1]]) {
                   ans -= c;
                   r--;
                   col[arr[i][1]] = false;
               }
               v.push(ans);
           }
           return v;
       }
 
       // Driver code
       let N = 3, Q = 3;
       let
           arr = [[2, 2], [2, 3], [3, 2]];
       let ans = countZero(N, Q, arr);
 
       for (let i = 0; i < ans.length; i++) {
           document.write(ans[i] + ' ');
       }
       document.write('<br>')
 
      // This code is contributed by Potta Lokesh
   </script>


 
 

Output: 

4 2 1

 

 

Time Complexity: O(K)
Space Complexity: O(N)

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads