Open In App

Minimum prefix toggles required to set all in a binary matrix

Last Updated : 06 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
C++
// C++ program to find minimum operations required
// to set all the elements of a binary matrix to 1
#include <bits/stdc++.h>
using namespace std;

// Return minimum operations required to 
// make all elements 1
int minOperation(vector<vector<int>> &mat) {
    
    int n = mat.size();
    int m = mat[0].size();
    int ans = 0;

    // Start from bottom-right and move to top-left
    for (int i = n - 1; i >= 0; i--) {
        for (int j = m - 1; j >= 0; j--) {

            // Check if current cell is 0
            if (mat[i][j] == 0) {
                
                // Increment operation count
                ans++;

                // Flip all elements from (0,0) to (i,j)
                for (int k = 0; k <= i; k++) {
                    for (int h = 0; h <= j; h++) {
                        
                        // Toggle the element
                        mat[k][h] = 1 - mat[k][h];
                    }
                }
            }
        }
    }

    return ans;
}

// Driver code
int main() {

    vector<vector<int>> 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}
    };

    cout << minOperation(mat) << endl;

    return 0;
}
Java
// Java program to find minimum operations required
// to set all the elements of a binary matrix to 1
class GfG {

    // Return minimum operations required to 
    // make all elements 1
    static int minOperation(int[][] mat) {

        int n = mat.length;
        int m = mat[0].length;
        int ans = 0;

        // Start from bottom-right and move to top-left
        for (int i = n - 1; i >= 0; i--) {
            for (int j = m - 1; j >= 0; j--) {

                // Check if current cell is 0
                if (mat[i][j] == 0) {

                    // Increment operation count
                    ans++;

                    // Flip all elements from (0,0) to (i,j)
                    for (int k = 0; k <= i; k++) {
                        for (int h = 0; h <= j; h++) {

                            // Toggle the element
                            mat[k][h] = 1 - mat[k][h];
                        }
                    }
                }
            }
        }

        return ans;
    }

    // Driver code
    public static void main(String[] args) {

        int[][] 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}
        };

        System.out.println(minOperation(mat));
    }
}
Python
# Python program to find minimum operations required
# to set all the elements of a binary matrix to 1

def minOperation(mat):

    n = len(mat)
    m = len(mat[0])
    ans = 0

    # Start from bottom-right and move to top-left
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):

            # Check if current cell is 0
            if mat[i][j] == 0:

                # Increment operation count
                ans += 1

                # Flip all elements from (0,0) to (i,j)
                for k in range(i + 1):
                    for h in range(j + 1):

                        # Toggle the element
                        mat[k][h] = 1 - mat[k][h]

    return ans

# Driver code
if __name__ == "__main__":

    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]
    ]

    print(minOperation(mat))
C#
// C# program to find minimum operations required
// to set all the elements of a binary matrix to 1
using System;

class GfG {

    // Return minimum operations required to 
    // make all elements 1
    public static int minOperation(int[,] mat) {

        int n = mat.GetLength(0);
        int m = mat.GetLength(1);
        int ans = 0;

        // Start from bottom-right and move to top-left
        for (int i = n - 1; i >= 0; i--) {
            for (int j = m - 1; j >= 0; j--) {

                // Check if current cell is 0
                if (mat[i,j] == 0) {

                    // Increment operation count
                    ans++;

                    // Flip all elements from (0,0) to (i,j)
                    for (int k = 0; k <= i; k++) {
                        for (int h = 0; h <= j; h++) {

                            // Toggle the element
                            mat[k,h] = 1 - mat[k,h];
                        }
                    }
                }
            }
        }

        return ans;
    }

    // Driver code
    public static void Main() {

        int[,] 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}
        };

        Console.WriteLine(minOperation(mat));
    }
}
JavaScript
// JavaScript program to find minimum operations required
// to set all the elements of a binary matrix to 1

function minOperation(mat) {

    let n = mat.length;
    let m = mat[0].length;
    let ans = 0;

    // Start from bottom-right and move to top-left
    for (let i = n - 1; i >= 0; i--) {
        for (let j = m - 1; j >= 0; j--) {

            // Check if current cell is 0
            if (mat[i][j] === 0) {

                // Increment operation count
                ans++;

                // Flip all elements from (0,0) to (i,j)
                for (let k = 0; k <= i; k++) {
                    for (let h = 0; h <= j; h++) {

                        // Toggle the element
                        mat[k][h] = 1 - mat[k][h];
                    }
                }
            }
        }
    }

    return ans;
}

// Driver code
const 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]
];

console.log(minOperation(mat));

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.


Article Tags :
Practice Tags :

Similar Reads