Related Articles

# Minimum number of operations required to set all elements of a binary matrix

• Last Updated : 25 Aug, 2020

Given a binary matrix mat[][] consisting of 1s and 0s of dimension M * N, the task is to find the number of operations to convert all 0s to 1s. In each operation, all the 1s can convert their adjacent 0s to 1s.

Note: Diagonal elements are not considered as adjacent elements of a number in the matrix.
Examples:

Input: mat[][] = {{0, 1, 1, 0, 1},
{0, 1, 0, 1, 0},
{0, 0, 0, 0, 1},
{0, 0, 1, 0, 0}}
Output: 2
Explanation: All the adjacent elements are in either left/right/up/down directions.
Matrix before the operations will be:
0 1 1 0 1
0 1 0 1 0
0 0 0 0 1
0 0 1 0 0

In the above example, operations would be as follows:
After Operation 1, the matrix will be:
1 1 1 1 1
1 1 1 1 1
0 1 1 1 1
0 1 1 1 1

After Operation 2, the matrix will be:
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Note: Numbers in bold indicate the modified 0s.

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

Approach:

1. Traverse the entire matrix and push the co-ordinates of the matrix elements with value 1 into a queue.
2. Save the size of the queue in variable x.
3. Traverse the queue for x iterations.
4. For each iteration, the position of an element with a value 1 is encountered. Convert the values in its adjacent positions to 1(only if the adjacent elements are 0) and then push the co-ordinates of the newly converted 1’s to the queue.
5. In each of the x iterations, dequeue the front element of the queue as soon as the step 4 is performed.
6. As soon as the x elements of the queue are traversed, increment the count of the number of operations to 1.
7. Repeat step 2 to step 6 till the queue is empty.
8. Return the count of the number of operations after the queue is empty. If the matrix has all 1s, no operation will be performed and the count will be 0.

Below is the implementation of the above approach.

## C++

 `// C++ code for the above approach.`` ` `#include ``using` `namespace` `std;`` ` `// function to check whether the``// adjacent neighbour is a valid``// index or not``bool` `check(``int` `row, ``int` `col, ``           ``int` `r, ``int` `c) {`` ` `    ``return` `(r >= 0 && r < row ``            ``&& c >= 0 && c < col);``}`` ` `// function to calculate the``// number of operations``int` `bfs(``int` `row, ``int` `col, ``        ``int` `*grid) {`` ` `    ``// direction matrix to find``    ``// adjacent neighbours``    ``int` `dir = { { 1, 0 }, ``                      ``{ -1, 0 }, ``                      ``{ 0, 1 }, ``                      ``{ 0, -1 } };`` ` `    ``// queue with pair to store``    ``// the indices of elements``    ``queue > q;`` ` `    ``// scanning the matrix to push``    ``// initial 1 elements``    ``for` `(``int` `i = 0; i < row; i++)``    ``{``        ``for` `(``int` `j = 0; ``             ``j < col; j++) {``             ` `          ``if` `(*((grid+i*col) + j))``            ``q.push(make_pair(i, j));``        ``}``    ``}`` ` `    ``// Step 2 to Step 6``    ``int` `op = -1;``    ``while` `(!q.empty()) {`` ` `      ``int` `x = q.size();``      ``for` `(``int` `k = 0; ``           ``k < x; k++) {``             ` `        ``pair<``int``, ``int``> p =``                 ``q.front();``        ``q.pop();`` ` `        ``// adding the values of``        ``// direction matrix to the ``        ``// current element to get``        ``// 4 possible adjacent``        ``// neighbours``        ``for` `(``int` `i = 0;``             ``i < 4; i++) {``                 ` `          ``int` `r = p.first +``                  ``dir[i];``          ``int` `c = p.second +``                  ``dir[i];`` ` `          ``// checking the validity``          ``// of the neighbour``          ``if` `(*((grid+r*col) + c) == 0 ``             ``&& check(row, col, r, c)) {``               ` `            ``// pushing it to the queue``            ``// and converting it to 1``            ``q.push(make_pair(r, c));``            ``*((grid+r*col) + c) = 1;``          ``}``        ``}``      ``}``      ``// increasing the operation by 1``      ``// after the first pass``      ``op++;``    ``}``    ``return` `op;``}`` ` `// Driver code``int` `main()``{``  ``int` `row = 4, col = 5;``  ``int` `grid[][col] = ``          ``{ { 0, 1, 1, 0, 1 },``            ``{ 0, 1, 0, 1, 0 },``            ``{ 0, 0, 0, 0, 1 },``            ``{ 0, 0, 1, 0, 0 } };``     ` `  ``cout << bfs(row, col, ``              ``(``int` `*)grid);``}`
Output:
```2
```

Time Complexity: O(M * N)
Auxiliary Space Complexity: O(M * N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up