VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-operations-required-set-elements-binary-matrix/

⇱ Minimum prefix toggles required to set all in a binary matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum prefix toggles required to set all in a binary matrix

Last Updated : 6 May, 2025

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.

Approach:

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:

  • Initialize n, m for matrix dimensions and ans = 0 to count the number of operations.
  • Loop from bottom-right to top-left to handle the most significant 0s first.
  • For each element mat[i][j], check if the value is 0 indicating a flip is required.
  • If a 0 is found, increment the operation count (ans) to reflect the new flip.
  • Loop through the submatrix (0,0) to (i,j) and flip each element using 1 - mat[k][h].
  • Continue until all elements are traversed and no 0s are left unprocessed.
  • Return the final count (ans) representing the minimum number of flip operations needed.

Output
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.

Comment
Article Tags: