Count of empty cells in given square Matrix after updating the rows and columns for Q queries
Last Updated :
10 Mar, 2022
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>
Time Complexity: O(K)
Space Complexity: O(N)
Similar Reads
Queries to find the count of connected Non-Empty Cells in a Matrix with updates Given a boolean matrix mat[][] consisting of N rows and M columns, initially filled with 0's(empty cells), an integer K and queries Q[][] of the type {X, Y}, the task is to replace mat[X][Y] = 1(non-empty cells) and count the number of connected non-empty cells from the given matrix.Examples: Input:
15+ min read
Queries to count sum of rows and columns of a Matrix present in given ranges Given a matrix A[][] of size N * M and a 2D array queries[][] consisting of Q queries of the form {L, R}, the task is to count the number of row-sums and column-sums which are an integer from the range [L, R]. Examples: Input: N = 2, M = 2, A[][] = {{1, 4}, {2, 5}}, Q = 2, queries[][] = {{3, 7}, {3,
14 min read
Count of ways to select K consecutive empty cells from a given Matrix Given a binary matrix V[][] of dimensions N * M, wherein each cell is either empty or blocked marked by a 0 and 1 respectively, the task is to count the number of ways to select K consecutive empty cells from the same row or column. Examples: Input: V[][] = {{1, 1, 0}, {0, 0, 0}}, K = 2 Output: 3 Ex
11 min read
Count of Ks in the Array for a given range of indices after array updates for Q queries Given an array arr[] of N integers, an integer K, and Q queries of the type as explained below: (1, L, R): If the query is of type 1, then find the number of Ks over the range [L, R].(2, P, X): If the query is of type 2, then update the array element at index P to X. The task is to perform the queri
15+ min read
Count of cells equal to X in Matrix constructed as sum of rows and columns Given integer N denoting the size of a square matrix whose each element is the sum of its row and column i.e., mat[i][j] = i + j (0 < i, j, ⤠N), and an integer X, the task is to find how many cells have the value X. Examples: Input: N = 4, X = 2Output: 1Explanation: The matrix we get after using
7 min read
Count rows in a matrix that consist of same element Given a matrix mat[][], the task is to count the number of rows in the matrix that consists of the same elements. Examples: Input: mat[][] = {{1, 1, 1}, {1, 2, 3}, {5, 5, 5}} Output: 2 All the elements of the first row and all the elements of the third row are the same. Input: mat[][] = {{1, 2}, {4,
9 min read
Binary Matrix after flipping submatrices in given range for Q queries Given a binary matrix arr[][] of dimensions M x N and Q queries of the form (x1, y1, x2, y2), where (x1, y1) and (x2, y2) denotes the top-left and bottom-right indices of the submatrix required to be flipped(convert 0s to 1s and vice versa) respectively. The task is to print the final matrix obtaine
15 min read
Program to find the Sum of each Row and each Column of a Matrix Given a matrix mat of size m à n, the task is to compute the sum of each row and each column of the matrix.Examples:Input: mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] Output: Sum of row 0 = 10 Sum of row 1 = 26 Sum of row 2 = 42 Sum of row 3 = 58 Sum of column 0 = 28 Sum
7 min read
Count regions after creating boundaries between adjacent cells of Matrix as per given queries Given a matrix of size N * M and Q queries, the task is to find how many different regions will be there, after performing the queries. In each query: There are four integers x1, y1, x2, y2 denoting two cells of the matrix (x1, y1) and (x2, y2) which are adjacent to each other.Create a boundary alon
15 min read
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns. Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this
15+ min read