Minimum time required to fill the entire matrix with 1’s


Given a matrix of size N consisting of 0‘s and 1‘s, the task is to find the minimum time required to fill the entire matrix with 1‘s. Every 1 at an instant in the matrix, can convert all 0‘s to 1 in its eight adjacent cells,i.e. a 1 present at (i,j) can convert all 0‘s to 1 at positions (i, j-1), (i, j+1), (i-1, j), (i+1, j), (i-1, j-1), (i-1, j+1), (i+1, j-1), (i+1, j+1).

Examples:

Input: N = 3, mtrx[][] = {{1,0,0},{0,0,1},{0,0,0}}
Output: 2
Explanation:
Initially the matrix appears to be
1, 0, 0
0, 0, 1
0, 0, 0
After the first instant of time, the new matrix is
1, 1, 1
1, 1, 1
0, 1, 1
After the 2nd instant the remaining 0 is converted to 1.

Input: N = 5,
mtrx[][] = {{0,0,0,0,0},
{1,0,0,0,0},
{0,0,0,0,0},
{0,0,1,0,0},
{0,0,0,1,0}}

Output: 3



Approach:
In order to solve this problem we are using the BFS approach. Traverse through the matrix and store the indices of the matrix with 1 initially in a queue. Loop until the queue gets empty and convert the adjacent valid cells of all queue elements to 1. The number of levels of BFS traversal that has led to conversion of at least one 0 to 1 is the answer.

Below code is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to calculate the number of steps
// in fill all entire matrix with '1'
#include<bits/stdc++.h>
using namespace std;
  
// Function to return total number 
// of steps required to fill
// entire matrix with '1'
int numberOfSteps(int n,vector<vector<int>> mtrx)
{
    // Queue to store indices with 1
    queue<pair<int,int>> q;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (mtrx[i][j] == 1) {
                q.push({i,j});
            }
        }
    }
      
    // Intialise step variable as zero
    int step = 0 ;
  
    // BFS approach
    while (!q.empty())
    {
        int qsize = q.size();
        // Visit all indices with 1 and
        // fill its neighbouring cells by 1
        while (qsize--) 
        {
            pair<int,int> p  = q.front();
            q.pop();
            int i = p.first;
            int j = p.second;
            // Convert the neighbour from '0' to '1'
            if((j > 0) && mtrx[i][j-1] == 0)
            {
                mtrx[i][j-1] = 1;
                q.push({i,j-1});
            }
            // Convert the neighbour from '0' to '1'
            if((i < n-1) && mtrx[i+1][j] == 0)
            {
                mtrx[i+1][j] = 1;
                q.push({i+1,j});
            }
            // Convert the neighbour from '0' to '1'
            if((j < n-1) && mtrx[i][j+1] == 0)
            {
                mtrx[i][j+1] = 1;
                q.push({i,j + 1});
            }
            // Convert the neighbour from '0' to '1'
            if((i > 0) && mtrx[i-1][j] == 0)
            {
                mtrx[i-1][j] = 1;
                q.push({i-1,j});
            }
            // Convert the neighbour from '0' to '1'
            if((i > 0) && (j > 0) && 
                                mtrx[i-1][j-1] == 0)
            {
                mtrx[i-1][j-1] = 1;
                q.push({i-1,j-1});
            }
            // Convert the neighbour from '0' to '1'
            if((i > 0) && (j < (n-1)) && 
                                mtrx[i-1][j+1] == 0)
            {
                mtrx[i-1][j+1] = 1;
                q.push({i-1,j+1});
            }
            // Convert the neighbour from '0' to '1'
            if((i < (n-1)) && (j < (n-1)) && 
                                mtrx[i+1][j+1] == 0)
            {
                mtrx[i+1][j+1] = 1;
                q.push({i+1,j + 1});
            }
            // Convert the neighbour from '0' to '1'
            if((i < (n-1)) && (j > 0) && 
                                mtrx[i+1][j-1] == 0)
            {
                mtrx[i+1][j-1] = 1;
                q.push({i+1,j-1});
            }
        
        //count steps
        step++;
    }
      
    return step-1;
}
  
// Driver code
int main()
{
    int n = 5 ; //dimension of matrix NXN
    vector<vector<int>> mtrx = {{0,0,0,0,0},
                                {1,0,0,0,0},
                                {0,0,0,0,0},
                                {0,0,1,0,0},
                                {0,0,0,1,0}};
    // Print number of steps
    cout << numberOfSteps(n, mtrx);
  
    return 0;
}

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to calculate the number of steps
# in fill all entire matrix with '1'
  
# Function to return total number 
# of steps required to fill
# entire matrix with '1'
def numberOfSteps(n,mtrx):
      
    # Queue to store indices with 1
    q = []
    for i in range(n):
        for j in range(n):
            if (mtrx[i][j] == 1):
                q.append([i,j])
      
    # Intialise step variable as zero
    step = 0
  
    # BFS approach
    while (len(q)):
        qsize = len(q)
          
        # Visit all indices with 1 and
        # fill its neighbouring cells by 1
        while(qsize):
            p = q[0]
            q.remove(q[0])
            i = p[0]
            j = p[1]
              
            # Convert the neighbour from '0' to '1'
            if((j > 0) and mtrx[i][j - 1] == 0):
                mtrx[i][j - 1] = 1
                q.append([i, j - 1])
                  
            # Convert the neighbour from '0' to '1'
            if((i < n-1) and mtrx[i + 1][j] == 0):
                mtrx[i + 1][j] = 1
                q.append([i + 1, j])
                  
            # Convert the neighbour from '0' to '1'
            if((j < n-1) and mtrx[i][j + 1] == 0):
                mtrx[i][j + 1] = 1
                q.append([i, j + 1])
                  
            # Convert the neighbour from '0' to '1'
            if((i > 0) and mtrx[i - 1][j] == 0):
                mtrx[i - 1][j] = 1
                q.append([i - 1, j])
                  
            # Convert the neighbour from '0' to '1'
            if((i > 0) and (j > 0) and 
                                   mtrx[i - 1][j - 1] == 0):
                mtrx[i - 1][j - 1] = 1
                q.append([i - 1, j - 1])
                  
            # Convert the neighbour from '0' to '1'
            if((i > 0) and (j < (n-1)) and  
                                    mtrx[i - 1][j + 1] == 0):
                mtrx[i - 1][j + 1] = 1
                q.append([i - 1, j + 1])
                  
            # Convert the neighbour from '0' to '1'
            if((i < (n - 1)) and (j < (n - 1)) and 
                                     mtrx[i + 1][j + 1] == 0):
                mtrx[i + 1][j + 1] = 1
                q.append([i + 1, j + 1])
                  
            # Convert the neighbour from '0' to '1'
            if((i < (n - 1)) and (j > 0) and
                                    mtrx[i + 1][j - 1] == 0):
                mtrx[i + 1][j - 1] = 1
                q.append([i + 1,j - 1])
              
            qsize -= 1
              
        #count steps
        step += 1
      
    return step-1
  
# Driver code
if __name__ == '__main__':
      
    #dimension of matrix NXN
    n = 5
    mtrx = [[ 0, 0, 0, 0, 0 ],
            [ 1, 0, 0, 0, 0 ],
            [ 0, 0, 0, 0, 0 ],
            [ 0, 0, 1, 0, 0 ],
            [ 0, 0, 0, 1, 0 ]]
              
    # Print number of steps
    print(numberOfSteps(n, mtrx))
      
# This code is contributed by Samarth

chevron_right


Output:

3

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ipg2016107