![]() |
VOOZH | about |
Given a binary matrix mat[][] of size n × m where each cell contains either 0 or 1. The allowed operation is to choose any position (x, y) and toggle all the elements in the submatrix from the top-left corner (0, 0) to the position (x-1, y-1). Toggling means changing a 0 to 1 and 1 to 0. The task is to determine the minimum number of such toggle operations required to make all elements of the matrix equal to 1.
Examples:
Input: mat[][] = 0 0 0 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output: 1
Explanation: One operation at position (3, 3) toggles the top-left 3×3 submatrix, converting all 0s to 1s.Input: mat[][] = 0 0 1 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output: 3
Explanation: Toggle at (3, 3) to flip the top-left 3×3 area. Then toggle at (2, 1) and (1, 1) to cover remaining 0s. Total 3 operations.
The idea is based on the observation that a zero at any position
(i, j)can only be flipped by applying an operation to the rectangle from (0,0) to (i,j). So, we start from the bottom-right and move to the top-left, and for each 0, we flip the entire submatrix above and to the left of it.
Steps to implement the above idea:
3
Time Complexity: O(n^2 *m^2), worst case flips entire submatrix for each 0.
Space Complexity: O(1), only a constant amount of extra space is used.