Given a Matrix size N*N and an integer K. Initially, the matrix contains only 0. You are given K tasks and for each task, you are given two coordinates (r, c). Where coordinates (r, c) denotes the rth row and the cth column of the given matrix. You have to perform each task sequentially in the given order. For each task, You have to put 1 in all rth row cells and all the cth column cells. After each task, You have to calculate the number of 0 present in the matrix and return it.
Input: N = 3, K = 3 1 1 1 2 2 1 Output: 4 2 1 Explanation: After 1st Operation, all the cells of the 2nd row and 2nd column will be filled by 1. So, the remaining cell with the value 0 will be 4. After 2nd operation, all the second row and all the third columns will be filled by 1. So, the remaining cell with value will be 2. After 3rd operation number of cells having the value 0 will be 1.
Input: N = 2, K = 2 0 1 0 0 Output: 1 0 Explanation: After 1st operation, all the cells of the 1st row and 2nd column will be filled by 1. So, the remaining cell with the value 0 will be 1. After 2nd operation, all the cells of the 1st row and 1st column will be filled by 1. So, the remaining cell with the value 0 will be 0.
Approach: The problem can be solved based on the following observation:
Idea is, if we fill one complete row with 1 (which was initially 0), then the size of every column reduce by 1. And if we fill one complete column with 1 (which was initially 0), then the size of every row reduce by 1.
Follow the steps mentioned below to implement the idea:
Initialize the vector, say ans, to store the number 0 after performing each operation.
Initialize two vectors, Row_vector, and Column_vector, to store the current information about, which row and column is a fields with 1.
Initialize two variable, say row_count and column_count, to store the number of row and column which is completely filed with 1.
Use a loop that will be running for k times, and perform the below operation.
Initialize two variables say, r and c inside the loop to store the row and column number on which the current operation is going to be performed.
If the value of Row_vector at index r is 0 then increase the row_count by 1, and assign 1 to Row_vector at index r.
If the value of Column_vector at index c is 0 then increase the column_count by 1, and assign 1 to Column_vector at index c.
Now calculate this term (n*n)-(row_count*n)-(column_count*n)+(row_count*column_count) each time.
Push the calculated term inside the ans vector.
Finally, print or return the ans vector.
Below is the Implementation of the above approach:
Please Login to comment...