Given a binary matrix of size N x M
, we need to find the minimum number of arrows require to remove all the 1's in the matrix.
Arrows can be hit vertically say at y = 6, It will remove all 1's at matrix[x][6]
, where 0 <= x < N
Or horizontally as well say at x = 5, It will remove all 1's at matrix[5][y]
, where 0 <= y < M
.
We need to find the minimum number of arrows require to remove all the 1's in the matrix.
Sample testcase :-
Input :
0 0 1 1 0 0
0 1 0 0 1 0
0 0 0 1 0 0
0 0 1 1 0 0
Output :
3
Explanation :
arrow-1 : x = 1
arrow-2 : y = 2
arrow-3 : y = 3
Approach(Greedy) :
We can count of number of 1's at each row and column and then sort them in decreasing order. And keep decreasing the arrow from the total arrow count until the count of the number of arrows reach to <= 0
. Can we can stop there and count the number of times we have done that operation.
But one issue with this approach, is arrows in rows and cols can overlap, thus we need someway to keep track of the num of arrows left in a row/column once we remove all the arrows from a row/col and keeping the array sorted at every instance, when update happens.
How can we solve this problem correctly and optimally ?