-3

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 ?

tusharRawat
  • 719
  • 10
  • 24
  • 1
    I'd think you'd want to choose an arrow to optimize the number of rows/cols remaining to be cleared, and not the number of 1's left. (And your test case "solution" leaves the 1 in the lower-right corner.) – Scott Hunter Jun 14 '22 at 18:57
  • Your solution x = 1, y = 2, y = 3 doesn't work IMO. The 1 at the corner i.e. (3, 5) is left. It has to be 4. – SomeDude Jun 14 '22 at 19:15

1 Answers1

0

I think the minimum can be found by:

Count the number of rows in which there are ones but those ones occur only in that row and no other row i.e. that’s the only 1 in that column, and keep track of the unique columns in which the ones occur.

In your example it is x = 1, the columns that has 1 in this case are y = 1, y = 4. total unique = 2

Then the result is (total number of columns - unique number of columns found in those rows counted above) In your example it is: 6 - 2 = 4

SomeDude
  • 13,876
  • 5
  • 21
  • 44