Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Feb, 2022
View Discussion
Improve Article
Save Article

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:
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 
0 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. 
 

 

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 <bits/stdc++.h>
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[4][2] = { { 1, 0 },
                      { -1, 0 },
                      { 0, 1 },
                      { 0, -1 } };
 
    // queue with pair to store
    // the indices of elements
    queue<pair<int, int> > 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][0];
          int c = p.second +
                  dir[i][1];
 
          // 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);
}

Java




// Java code for the above approach.
import java.util.*;
 
class GFG{
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
   
// function to check whether the
// adjacent neighbour is a valid
// index or not
static boolean 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
static 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<pair > q = new LinkedList<GFG.pair>();
 
    // 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][j]!=0)
            q.add(new pair(i, j));
        }
    }
 
    // Step 2 to Step 6
    int op = -1;
    while (!q.isEmpty()) {
 
      int x = q.size();
      for (int k = 0;
           k < x; k++) {
             
        pair p =
                 q.peek();
        q.remove();
 
        // 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][0];
          int c = p.second +
                  dir[i][1];
 
          // checking the validity
          // of the neighbour
          if (check(row, col, r, c) && grid[r] == 0) {
               
            // pushing it to the queue
            // and converting it to 1
            q.add(new pair(r, c));
            grid[r] = 1;
          }
        }
      }
       
      // increasing the operation by 1
      // after the first pass
      op++;
    }
    return op;
}
 
// Driver code
public static void main(String[] args)
{
  int row = 4, col = 5;
  int grid[][] =
          { { 0, 1, 1, 0, 1 },
            { 0, 1, 0, 1, 0 },
            { 0, 0, 0, 0, 1 },
            { 0, 0, 1, 0, 0 } };
     
  System.out.print(bfs(row, col,
              grid));
}
}
 
// This code is contributed by shikhasingrajput

Python3




# Python 3 code for the above approach.
 
# function to check whether the
# adjacent neighbour is a valid
# index or not
def check(row, col, r, c):
    return (r >= 0 and r < row
            and c >= 0 and c < col)
 
# function to calculate the
# number of operations
def bfs(row, col, grid):
 
    # direction matrix to find
    # adjacent neighbours
    dir = [[1, 0],
           [-1, 0],
           [0, 1],
           [0, -1]]
 
    # queue with pair to store
    # the indices of elements
    q = []
 
    # scanning the matrix to push
    # initial 1 elements
    for i in range(row):
        for j in range(col):
            if (grid[i][j]):
                q.insert(0, [i, j])
 
 
    # Step 2 to Step 6
    op = -1
    while (len(q) != 0):
        x = len(q)
        for k in range(x):
            p = q[0]
            q.pop(0)
 
            # adding the values of
            # direction matrix to the
            # current element to get
            # 4 possible adjacent
            # neighbours
            for i in range(4):
                r = p[0] + dir[i][0]
                c = p[1] + dir[i][1]
 
                # checking the validity
                # of the neighbour
                if (check(row, col, r, c)
                        and grid[r] == 0 ):
 
                    # pushing it to the queue
                    # and converting it to 1
                    q.insert(0, [r, c])
                    grid[r] = 1
 
        # increasing the operation by 1
        # after the first pass
        op += 1
 
    return op
    #return 0
 
# Driver code
if __name__ == "__main__":
 
    row = 4
    col = 5
    grid = [[0, 1, 1, 0, 1],
            [0, 1, 0, 1, 0],
            [0, 0, 0, 0, 1],
            [0, 0, 1, 0, 0]]
 
    print(bfs(row, col,
              grid))
 
    # This code is contributed by ukasp.

C#




// C# code for the above approach.
using System;
using System.Collections.Generic;
 
public class GFG{
  class pair
  {
    public int first, second;
    public pair(int first, int second) 
    {
      this.first = first;
      this.second = second;
    }   
  }
 
  // function to check whether the
  // adjacent neighbour is a valid
  // index or not
  static 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
  static 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
    List<pair > q = new List<pair>();
 
    // 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,j]!=0)
          q.Add(new pair(i, j));
      }
    }
 
    // Step 2 to Step 6
    int op = -1;
    while (q.Count!=0) {
 
      int x = q.Count;
      for (int k = 0;
           k < x; k++) {
 
        pair p =
          q[0];
        q.RemoveAt(0);
 
        // 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,0];
          int c = p.second +
            dir[i,1];
 
          // checking the validity
          // of the neighbour
          if (check(row, col, r, c) && grid[r,c] == 0) {
 
            // pushing it to the queue
            // and converting it to 1
            q.Add(new pair(r, c));
            grid[r,c] = 1;
          }
        }
      }
 
      // increasing the operation by 1
      // after the first pass
      op++;
    }
    return op;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int row = 4, col = 5;
    int [,]grid =
    { { 0, 1, 1, 0, 1 },
     { 0, 1, 0, 1, 0 },
     { 0, 0, 0, 0, 1 },
     { 0, 0, 1, 0, 0 } };
 
    Console.Write(bfs(row, col,
                      grid));
  }
}
 
// This code is contributed by shikhasingrajput

Output: 

2

 

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!