# Minimum operations required to set all elements of binary matrix

Given a binary matrix of N rows and M columns. The operation allowed on the matrix is to choose any index (x, y) and toggle all the elements between the rectangle having top-left as (0, 0) and bottom-right as (x-1, y-1). Toggling the element means changing 1 to 0 and 0 to 1. The task is to find minimum operations required to make set all the elements of the matrix i.e make all elements as 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
In one move, choose (3, 3) to make the
whole matrix consisting of only 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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to start from the end point (N – 1, M – 1) and traverse the matrix in reverse order. Whenever we encounter a cell which has a value of 0, flip it.
Why traversing from end point ?
Suppose there are 0 at (x, y) and (x + 1, y + 1) cell. You shouldn’t flip a cell (x + 1, y + 1) after cell (x, y) because after you flipped (x, y) to 1, in next move to flip (x + 1, y + 1) cell, you will flip again (x, y) to 0. So there is no benefit from the first move for flipping (x, y) cell.

Below is implementation of this approach:

## C++

 `// C++ program to find minimum operations required ` `// to set all the element of binary matrix ` `#include ` `#define N 5 ` `#define M 5 ` `using` `namespace` `std; ` ` `  `// Return minimum operation required to make all 1s. ` `int` `minOperation(``bool` `arr[N][M]) ` `{ ` `    ``int` `ans = 0; ` `    ``for` `(``int` `i = N - 1; i >= 0; i--) ` `    ``{ ` `        ``for` `(``int` `j = M - 1; j >= 0; j--) ` `        ``{ ` `            ``// check if this cell equals 0 ` `            ``if``(arr[i][j] == 0) ` `            ``{ ` `                ``// increase the number of moves ` `                ``ans++; ` ` `  `                ``// flip from this cell to the start point ` `                ``for` `(``int` `k = 0; k <= i; k++) ` `                ``{ ` `                    ``for` `(``int` `h = 0; h <= j; h++) ` `                    ``{ ` `                        ``// flip the cell ` `                        ``if` `(arr[k][h] == 1) ` `                            ``arr[k][h] = 0; ` `                        ``else` `                            ``arr[k][h] = 1; ` `                    ``} ` `                ``} ` `            ``} ` `        ``} ` `    ``} ` `    ``return` `ans; ` `} ` ` `  `// Driven Program ` `int` `main() ` `{ ` `    ``bool` `mat[N][M] = ` `    ``{ ` `        ``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 element of binary matrix  ` ` `  `class` `GFG { ` ` `  `    ``static` `final` `int` `N = ``5``; ` `    ``static` `final` `int` `M = ``5``; ` ` `  `// Return minimum operation required to make all 1s.  ` `    ``static` `int` `minOperation(``boolean` `arr[][])  ` `    ``{ ` `        ``int` `ans = ``0``; ` `        ``for` `(``int` `i = N - ``1``; i >= ``0``; i--)  ` `        ``{ ` `            ``for` `(``int` `j = M - ``1``; j >= ``0``; j--) ` `            ``{ ` `                ``// check if this cell equals 0  ` `                ``if` `(arr[i][j] == ``false``)  ` `                ``{ ` `                    ``// increase the number of moves  ` `                    ``ans++; ` ` `  `                    ``// flip from this cell to the start point  ` `                    ``for` `(``int` `k = ``0``; k <= i; k++) ` `                    ``{ ` `                        ``for` `(``int` `h = ``0``; h <= j; h++)  ` `                        ``{ ` `                            ``// flip the cell  ` `                            ``if` `(arr[k][h] == ``true``)  ` `                            ``{ ` `                                ``arr[k][h] = ``false``; ` `                            ``} ``else` `{ ` `                                ``arr[k][h] = ``true``; ` `                            ``} ` `                        ``} ` `                    ``} ` `                ``} ` `            ``} ` `        ``} ` `        ``return` `ans; ` `    ``} ` ` `  `// Driven Program  ` `    ``public` `static` `void` `main(String[] args) { ` ` `  `        ``boolean` `mat[][] ` `                ``= { ` `                    ``{``false``, ``false``, ``true``, ``true``, ``true``}, ` `                    ``{``false``, ``false``, ``false``, ``true``, ``true``}, ` `                    ``{``false``, ``false``, ``false``, ``true``, ``true``}, ` `                    ``{``true``, ``true``, ``true``, ``true``, ``true``}, ` `                    ``{``true``, ``true``, ``true``, ``true``, ``true``} ` `                ``}; ` ` `  `        ``System.out.println(minOperation(mat)); ` `    ``} ` `} ` ` `  `// This code is contributed  ` `// by PrinciRaj1992 `

## Python 3

 `# Python 3 program to find ` `# minimum operations required ` `# to set all the element of ` `# binary matrix ` ` `  `# Return minimum operation  ` `# required to make all 1s. ` `def` `minOperation(arr): ` `    ``ans ``=` `0` `    ``for` `i ``in` `range``(N ``-` `1``, ``-``1``, ``-``1``): ` `        ``for` `j ``in` `range``(M ``-` `1``, ``-``1``, ``-``1``): ` `             `  `            ``# check if this  ` `            ``# cell equals 0 ` `            ``if``(arr[i][j] ``=``=` `0``): ` `     `  `                ``# increase the ` `                ``# number of moves ` `                ``ans ``+``=` `1` ` `  `                ``# flip from this cell  ` `                ``# to the start point ` `                ``for` `k ``in` `range``(i ``+` `1``): ` `                    ``for` `h ``in` `range``(j ``+` `1``): ` `                     `  `                        ``# flip the cell ` `                        ``if` `(arr[k][h] ``=``=` `1``): ` `                            ``arr[k][h] ``=` `0` `                        ``else``: ` `                            ``arr[k][h] ``=` `1` `                     `  `    ``return` `ans ` ` `  `# Driver Code ` `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``]] ` `M ``=` `5` `N ``=` `5` ` `  `print``(minOperation(mat)) ` ` `  `# This code is contributed ` `# by ChitraNayal `

## C#

 `using` `System; ` ` `  `// C# program to find minimum operations required   ` `// to set all the element of binary matrix   ` ` `  `public` `class` `GFG ` `{ ` ` `  `    ``public` `const` `int` `N = 5; ` `    ``public` `const` `int` `M = 5; ` ` `  `// Return minimum operation required to make all 1s.   ` `    ``public` `static` `int` `minOperation(``bool``[][] arr) ` `    ``{ ` `        ``int` `ans = 0; ` `        ``for` `(``int` `i = N - 1; i >= 0; i--) ` `        ``{ ` `            ``for` `(``int` `j = M - 1; j >= 0; j--) ` `            ``{ ` `                ``// check if this cell equals 0   ` `                ``if` `(arr[i][j] == ``false``) ` `                ``{ ` `                    ``// increase the number of moves   ` `                    ``ans++; ` ` `  `                    ``// flip from this cell to the start point   ` `                    ``for` `(``int` `k = 0; k <= i; k++) ` `                    ``{ ` `                        ``for` `(``int` `h = 0; h <= j; h++) ` `                        ``{ ` `                            ``// flip the cell   ` `                            ``if` `(arr[k][h] == ``true``) ` `                            ``{ ` `                                ``arr[k][h] = ``false``; ` `                            ``} ` `                            ``else` `                            ``{ ` `                                ``arr[k][h] = ``true``; ` `                            ``} ` `                        ``} ` `                    ``} ` `                ``} ` `            ``} ` `        ``} ` `        ``return` `ans; ` `    ``} ` ` `  `// Driven Program   ` `    ``public` `static` `void` `Main(``string``[] args) ` `    ``{ ` ` `  `        ``bool``[][] mat = ``new` `bool``[][] ` `        ``{ ` `            ``new` `bool``[] {``false``, ``false``, ``true``, ``true``, ``true``}, ` `            ``new` `bool``[] {``false``, ``false``, ``false``, ``true``, ``true``}, ` `            ``new` `bool``[] {``false``, ``false``, ``false``, ``true``, ``true``}, ` `            ``new` `bool``[] {``true``, ``true``, ``true``, ``true``, ``true``}, ` `            ``new` `bool``[] {``true``, ``true``, ``true``, ``true``, ``true``} ` `        ``}; ` ` `  `        ``Console.WriteLine(minOperation(mat)); ` `    ``} ` `} ` ` `  `// This code is contributed by Shrikant13 `

## PHP

 `= 0; ``\$i``--) ` `    ``{ ` `        ``for` `(``\$j` `= ``\$M` `- 1; ` `             ``\$j` `>= 0; ``\$j``--) ` `        ``{ ` `            ``// check if this ` `            ``// cell equals 0 ` `            ``if``(``\$arr``[``\$i``][``\$j``] == 0) ` `            ``{ ` `                ``// increase the ` `                ``// number of moves ` `                ``\$ans``++; ` ` `  `                ``// flip from this cell  ` `                ``// to the start point ` `                ``for` `(``\$k` `= 0;  ` `                     ``\$k` `<= ``\$i``; ``\$k``++) ` `                ``{ ` `                    ``for` `(``\$h` `= 0; ` `                         ``\$h` `<= ``\$j``; ``\$h``++) ` `                    ``{ ` `                        ``// flip the cell ` `                        ``if` `(``\$arr``[``\$k``][``\$h``] == 1) ` `                            ``\$arr``[``\$k``][``\$h``] = 0; ` `                        ``else` `                            ``\$arr``[``\$k``][``\$h``] = 1; ` `                    ``} ` `                ``} ` `            ``} ` `        ``} ` `    ``} ` `    ``return` `\$ans``; ` `} ` ` `  `// Driver Code ` `\$mat` `= ``array``(``array``(0, 0, 1, 1, 1), ` `             ``array``(0, 0, 0, 1, 1), ` `             ``array``(0, 0, 0, 1, 1), ` `             ``array``(1, 1, 1, 1, 1), ` `             ``array``(1, 1, 1, 1, 1)); ` ` `  `echo` `minOperation(``\$mat``); ` ` `  `// This code is contributed  ` `// by ChitraNayal ` `?> `

Output:

```3
```

Time Complexity: O(N2 * M2).
Space Complexity: O(N*M).

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5549226,"math_prob":0.9716349,"size":7219,"snap":"2019-51-2020-05","text_gpt3_token_len":2634,"char_repetition_ratio":0.14691615,"word_repetition_ratio":0.39915714,"special_character_ratio":0.40324146,"punctuation_ratio":0.171246,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99968636,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-09T00:26:43Z\",\"WARC-Record-ID\":\"<urn:uuid:621fc740-2c11-4a88-bb70-ed489d403859>\",\"Content-Length\":\"199975\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:7baf862d-98a1-4e42-b897-b3167e96d300>\",\"WARC-Concurrent-To\":\"<urn:uuid:a9c68da9-9d0a-4097-a7c9-69159507a53c>\",\"WARC-IP-Address\":\"23.62.60.179\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/minimum-operations-required-set-elements-binary-matrix/\",\"WARC-Payload-Digest\":\"sha1:Y2U6EPZKFKCPNBQ7K7LE2ESWVONSAGZE\",\"WARC-Block-Digest\":\"sha1:UI4K2GZVKLWL5LMEXPWV4LS2Q3IVMNR4\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540515344.59_warc_CC-MAIN-20191208230118-20191209014118-00374.warc.gz\"}"}