Minimum number of operations required to set all elements of a binary matrix
Last Updated :
15 Jul, 2025
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][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 } };
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][c] == 0 ):
# pushing it to the queue
# and converting it to 1
q.insert(0, [r, c])
grid[r][c] = 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][c] === 0) {
// pushing it to the queue
// and converting it to 1
q.unshift([r, c]);
grid[r][c] = 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
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][c] = 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][c] = 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][c] = 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][c] = 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][c] = 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
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][c] = 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][c] = 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][c] = 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][c] = 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][c] = 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));
Time Complexity: O(M * N)
Auxiliary Space: O(M * N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem