Minimum number of operations required to set all elements of a binary matrix
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.
Approach:
- Traverse the entire matrix and push the co-ordinates of the matrix elements with value 1 into a queue.
- Save the size of the queue in variable x.
- Traverse the queue for x iterations.
- 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.
- In each of the x iterations, dequeue the front element of the queue as soon as the step 4 is performed.
- As soon as the x elements of the queue are traversed, increment the count of the number of operations to 1.
- Repeat step 2 to step 6 till the queue is empty.
- 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 |
Javascript
// function to check whether the // adjacent neighbour is a valid // index or not function check(row, col, r, c) { return (r >= 0 && r < row && c >= 0 && c < col); } // function to calculate the // number of operations function bfs(row, col, grid) { // direction matrix to find // adjacent neighbours const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]]; // queue with pair to store // the indices of elements const q = []; // scanning the matrix to push // initial 1 elements for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { if (grid[i][j]) { q.unshift([i, j]); } } } // Step 2 to Step 6 let op = -1; while (q.length !== 0) { const x = q.length; for (let k = 0; k < x; k++) { const p = q.shift(); // adding the values of // direction matrix to the // current element to get // 4 possible adjacent // neighbours for (let i = 0; i < 4; i++) { const r = p[0] + dir[i][0]; const c = p[1] + 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.unshift([r, c]); grid[r] = 1; } } } // increasing the operation by 1 // after the first pass op++; } return op; } // Driver code const row = 4; const col = 5; const grid = [[0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0] ]; console.log(bfs(row, col, grid)); // This code is contributed by Prince Kumar |
2
Time Complexity: O(M * N)
Auxiliary Space Complexity: O(M * N)
Approach 2:
This approach uses a recursive depth-first search (DFS) function to visit all connected cells with a value of 0. It starts by traversing the grid and whenever a 0 cell is found, it performs a DFS to visit all adjacent 0 cells. Each time a DFS is performed, it increments the count by 1. Finally, it returns the count minus 1 because the initial 1 cells are not considered as operations.
Note: This code assumes that the grid size is fixed and known at compile time. If you want to make it more dynamic, you can use dynamic memory allocation or containers like std::vector to handle the grid size dynamically.
C++
#include <iostream> #include <vector> 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); } // DFS function to visit all connected cells void dfs( int r, int c, int row, int col, vector<vector< int > >& grid) { // Mark the cell as visited grid[r] = 1; // Define the possible adjacent neighbours int dr[] = { 1, -1, 0, 0 }; int dc[] = { 0, 0, 1, -1 }; // Visit all adjacent neighbours for ( int i = 0; i < 4; i++) { int nr = r + dr[i]; int nc = c + dc[i]; // Check if the neighbour is valid and has a 0 value if (check(row, col, nr, nc) && grid[nr][nc] == 0) { dfs(nr, nc, row, col, grid); } } } // Function to calculate the number of operations int countOperations( int row, int col, vector<vector< int > >& grid) { int count = 0; // Traverse the grid for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { // If a cell is 0, perform DFS to visit all // connected cells if (grid[i][j] == 0) { dfs(i, j, row, col, grid); count++; } } } return count - 1; // Subtract 1 because the initial 1 cells // are not considered as operations } // Driver code int main() { int row = 4, col = 5; vector<vector< int > > grid = { { 0, 1, 1, 0, 1 }, { 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 1 }, { 0, 0, 1, 0, 0 } }; cout << countOperations(row, col, grid) << endl; return 0; } |
Java
// Java implementation import java.util.*; public class Main { // 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); } // DFS function to visit all connected cells static void dfs( int r, int c, int row, int col, int [][] grid, boolean [][] visited) { // Mark the cell as visited visited[r] = true ; // Define the possible adjacent neighbours int [] dr = { 1 , - 1 , 0 , 0 }; int [] dc = { 0 , 0 , 1 , - 1 }; // Visit all adjacent neighbours for ( int i = 0 ; i < 4 ; i++) { int nr = r + dr[i]; int nc = c + dc[i]; // Check if the neighbour is valid and has a 0 value if (check(row, col, nr, nc) && grid[nr][nc] == 0 && !visited[nr][nc]) { dfs(nr, nc, row, col, grid, visited); } } } // Function to calculate the number of operations static int countOperations( int row, int col, int [][] grid) { int count = 0 ; boolean [][] visited = new boolean [row][col]; // Traverse the grid for ( int i = 0 ; i < row; i++) { for ( int j = 0 ; j < col; j++) { // If a cell is 0 and not visited, // perform DFS to visit all // connected cells if (grid[i][j] == 0 && !visited[i][j]) { dfs(i, j, row, col, grid, visited); count++; } } } return count - 1 ; // Subtract 1 because the initial 1 cells // are not considered as operations } // 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.println(countOperations(row, col, grid)); } } // This code is contributed by Pushpesh Raj |
Python3
# python code def check(row, col, r, c): # Function to check whether the adjacent neighbour is a valid index or not return r > = 0 and r < row and c > = 0 and c < col def dfs(r, c, row, col, grid): # DFS function to visit all connected cells # Mark the cell as visited grid[r] = 1 # Define the possible adjacent neighbours dr = [ 1 , - 1 , 0 , 0 ] dc = [ 0 , 0 , 1 , - 1 ] # Visit all adjacent neighbours for i in range ( 4 ): nr = r + dr[i] nc = c + dc[i] # Check if the neighbour is valid and has a 0 value if check(row, col, nr, nc) and grid[nr][nc] = = 0 : dfs(nr, nc, row, col, grid) def countOperations(row, col, grid): # Function to calculate the number of operations count = 0 # Traverse the grid for i in range (row): for j in range (col): # If a cell is 0, perform DFS to visit all connected # cells if grid[i][j] = = 0 : dfs(i, j, row, col, grid) count + = 1 return count - 1 # Subtract 1 because the initial 1 cells are not considered as operations # Driver code 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 (countOperations(row, col, grid)) # This code is contributed by akshitaguprzj3 |
C#
using System; using System.Collections.Generic; class Program { // 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); } // DFS function to visit all connected cells static void DFS( int r, int c, int row, int col, List<List< int > > grid) { // Mark the cell as visited grid[r] = 1; // Define the possible adjacent neighbours int [] dr = { 1, -1, 0, 0 }; int [] dc = { 0, 0, 1, -1 }; // Visit all adjacent neighbours for ( int i = 0; i < 4; i++) { int nr = r + dr[i]; int nc = c + dc[i]; // Check if the neighbour is valid and has a 0 // value if (Check(row, col, nr, nc) && grid[nr][nc] == 0) { DFS(nr, nc, row, col, grid); } } } // Function to calculate the number of operations static int CountOperations( int row, int col, List<List< int > > grid) { int count = 0; // Traverse the grid for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { // If a cell is 0, perform DFS to visit all // connected cells if (grid[i][j] == 0) { DFS(i, j, row, col, grid); count++; } } } return count - 1; // Subtract 1 because the initial 1 cells // are not considered as operations } // Driver code static void Main( string [] args) { int row = 4, col = 5; List<List< int > > grid = new List<List< int > >() { new List< int >() { 0, 1, 1, 0, 1 }, new List< int >() { 0, 1, 0, 1, 0 }, new List< int >() { 0, 0, 0, 0, 1 }, new List< int >() { 0, 0, 1, 0, 0 } }; Console.WriteLine(CountOperations(row, col, grid)); } } // This code is contributed by akshitaguprzj3 |
Javascript
// Javascript code for abvove approach // Function to check whether the // adjacent neighbour is a valid index or not function check(row, col, r, c) { return (r >= 0 && r < row && c >= 0 && c < col); } // DFS function to visit all connected cells function dfs(r, c, row, col, grid) { // Mark the cell as visited grid[r] = 1; // Define the possible adjacent neighbours let dr = [ 1, -1, 0, 0 ]; let dc = [ 0, 0, 1, -1 ]; // Visit all adjacent neighbours for (let i = 0; i < 4; i++) { let nr = r + dr[i]; let nc = c + dc[i]; // Check if the neighbour is valid and has a 0 value if (check(row, col, nr, nc) && grid[nr][nc] == 0) { dfs(nr, nc, row, col, grid); } } } // Function to calculate the number of operations function countOperations(row, col, grid) { let count = 0; // Traverse the grid for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { // If a cell is 0, perform DFS to visit all // connected cells if (grid[i][j] == 0) { dfs(i, j, row, col, grid); count++; } } } return count - 1; // Subtract 1 because the initial 1 cells // are not considered as operations } // Driver code let row = 4; let col = 5; let grid = [ [0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0] ]; console.log(countOperations(row, col, grid)); // This code is contributed by Vaibhav Nandan |
2
Time Complexity: O(M * N)
Auxiliary Space Complexity: O(M * N)
Approach-Breath First Search:
BFS Approach uses a queue to perform breadth-first traversal of the grid. The bfs function pushes the starting cell into the queue, marks it as visited, and then iterates over the adjacent neighbors using a loop. Each valid neighbor with a value of 0 is pushed into the queue and marked as visited.It will count the number of connected components (groups of adjacent 0 cells) in the grid.
Here is the code of above approach:
C++
#include <iostream> #include <vector> #include <queue> 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); } // BFS function to visit all connected cells void bfs( int r, int c, int row, int col, vector<vector< int >>& grid) { queue<pair< int , int >> q; q.push({r, c}); grid[r] = 1; // Mark the cell as visited // Define the possible adjacent neighbours int dr[] = {1, -1, 0, 0}; int dc[] = {0, 0, 1, -1}; while (!q.empty()) { int currRow = q.front().first; int currCol = q.front().second; q.pop(); // Visit all adjacent neighbours for ( int i = 0; i < 4; i++) { int nr = currRow + dr[i]; int nc = currCol + dc[i]; // Check if the neighbour is valid and has a 0 value if (check(row, col, nr, nc) && grid[nr][nc] == 0) { q.push({nr, nc}); grid[nr][nc] = 1; // Mark the cell as visited } } } } // Function to calculate the number of operations int countOperations( int row, int col, vector<vector< int >>& grid) { int count = 0; // Traverse the grid for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { // If a cell is 0, perform BFS to visit all connected cells if (grid[i][j] == 0) { bfs(i, j, row, col, grid); count++; } } } return count - 1; // Subtract 1 because the initial 1 cells are not considered as operations } // Driver code int main() { int row = 4, col = 5; vector<vector< int >> grid = { {0, 1, 1, 0, 1}, {0, 1, 0, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 1, 0, 0} }; cout << countOperations(row, col, grid) << endl; return 0; } |
Java
import java.util.LinkedList; import java.util.Queue; public class Main { // Function to check whether the adjacent neighbor 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); } // BFS function to visit all connected cells static void bfs( int r, int c, int row, int col, int [][] grid) { Queue< int []> q = new LinkedList<>(); q.add( new int [] { r, c }); grid[r] = 1 ; // Mark the cell as visited // Define the possible adjacent neighbors int [] dr = { 1 , - 1 , 0 , 0 }; int [] dc = { 0 , 0 , 1 , - 1 }; while (!q.isEmpty()) { int [] currCell = q.poll(); int currRow = currCell[ 0 ]; int currCol = currCell[ 1 ]; // Visit all adjacent neighbors for ( int i = 0 ; i < 4 ; i++) { int nr = currRow + dr[i]; int nc = currCol + dc[i]; // Check if the neighbor is valid and has a // 0 value if (check(row, col, nr, nc) && grid[nr][nc] == 0 ) { q.add( new int [] { nr, nc }); grid[nr][nc] = 1 ; // Mark the cell as visited } } } } // Function to calculate the number of operations static int countOperations( int row, int col, int [][] grid) { int count = 0 ; // Traverse the grid for ( int i = 0 ; i < row; i++) { for ( int j = 0 ; j < col; j++) { // If a cell is 0, perform BFS to visit all // connected cells if (grid[i][j] == 0 ) { bfs(i, j, row, col, grid); count++; } } } return count - 1 ; // Subtract 1 because the initial 1 cells // are not considered as operations } 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.println(countOperations(row, col, grid)); } } |
Python3
from collections import deque # Function to check whether the adjacent neighbour is a valid index or not def check(row, col, r, c): return 0 < = r < row and 0 < = c < col # BFS function to visit all connected cells def bfs(r, c, row, col, grid): q = deque([(r, c)]) grid[r] = 1 # Mark the cell as visited # Define the possible adjacent neighbours dr = [ 1 , - 1 , 0 , 0 ] dc = [ 0 , 0 , 1 , - 1 ] while q: currRow, currCol = q.popleft() # Visit all adjacent neighbours for i in range ( 4 ): nr = currRow + dr[i] nc = currCol + dc[i] # Check if the neighbour is valid and has a 0 value if check(row, col, nr, nc) and grid[nr][nc] = = 0 : q.append((nr, nc)) grid[nr][nc] = 1 # Mark the cell as visited # Function to calculate the number of operations def countOperations(row, col, grid): count = 0 # Traverse the grid for i in range (row): for j in range (col): # If a cell is 0, perform BFS to visit all connected cells if grid[i][j] = = 0 : bfs(i, j, row, col, grid) count + = 1 return count - 1 # Subtract 1 because the initial 1 cells are not considered as operations # 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 (countOperations(row, col, grid)) |
C#
using System; using System.Collections.Generic; class Program { static bool Check( int row, int col, int r, int c) { return (r >= 0 && r < row && c >= 0 && c < col); } static void BFS( int r, int c, int row, int col, int [][] grid) { Queue<( int , int )> q = new Queue<( int , int )>(); q.Enqueue((r, c)); grid[r] = 1; int [] dr = { 1, -1, 0, 0 }; int [] dc = { 0, 0, 1, -1 }; while (q.Count > 0) { ( int currRow, int currCol) = q.Dequeue(); for ( int i = 0; i < 4; i++) { int nr = currRow + dr[i]; int nc = currCol + dc[i]; if (Check(row, col, nr, nc) && grid[nr][nc] == 0) { q.Enqueue((nr, nc)); grid[nr][nc] = 1; } } } } static int CountOperations( int row, int col, int [][] grid) { int count = 0; for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { if (grid[i][j] == 0) { BFS(i, j, row, col, grid); count++; } } } return count - 1; } static void Main() { int row = 4, col = 5; int [][] grid = { new int [] { 0, 1, 1, 0, 1 }, new int [] { 0, 1, 0, 1, 0 }, new int [] { 0, 0, 0, 0, 1 }, new int [] { 0, 0, 1, 0, 0 } }; Console.WriteLine(CountOperations(row, col, grid)); } } |
Javascript
function GFG(row, col, r, c) { return r >= 0 && r < row && c >= 0 && c < col; } // BFS function to visit // all connected cells function bfs(r, c, row, col, grid) { const queue = [[r, c]]; grid[r] = 1; // Define the possible // adjacent neighbours const dr = [1, -1, 0, 0]; const dc = [0, 0, 1, -1]; while (queue.length > 0) { const [currRow, currCol] = queue.shift(); // Visit all adjacent neighbours for (let i = 0; i < 4; i++) { const nr = currRow + dr[i]; const nc = currCol + dc[i]; // Check if the neighbour is // valid and has a 0 value if (GFG(row, col, nr, nc) && grid[nr][nc] === 0) { queue.push([nr, nc]); grid[nr][nc] = 1; } } } } // Function to calculate the number of operations function Geek(row, col, grid) { let count = 0; // Traverse the grid for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { // If a cell is 0, perform BFS to // visit all connected cells if (grid[i][j] === 0) { bfs(i, j, row, col, grid); count++; } } } return count - 1; // Subtract 1 because the initial 1 cells are // not considered as operations } // Driver code const row = 4, col = 5; const grid = [ [0, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 1, 0, 0] ]; console.log(Geek(row, col, grid)); |
2
Time Complexity: O(M * N)
Auxiliary Space: O(M * N)
Contact Us