Distance of nearest cell having 1 in a binary matrix
Last Updated :
30 Jan, 2023
Given a binary matrix of N x M, containing at least a value 1. The task is to find the distance of the nearest 1 in the matrix for each cell. The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1
Examples:
Input: N = 3, M = 4
mat[][] = { {0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 0} }
Output:
3 2 1 0
2 1 0 0
1 0 0 1
Explanation: For cell at (0, 0), nearest 1 is at (0, 3).
So distance = (0 – 0) + (3 – 0) = 3.
Similarly, all the distance can be calculated
Input: N = 3, M = 3
mat[][] = { {1, 0, 0}, {0, 0, 1}, {0, 1, 1} }
Output:
0 1 1
1 1 0
1 0 0
Explanation: For cell at (0, 1), nearest 1 is at (0, 0).
So distance is 1. Similarly, all the distance can be calculated.
Naive Approach: To solve the problem follow the below idea:
The idea is to traverse the matrix for each cell and find the minimum distance, To find the minimum distance traverse the matrix and find the cell which contains 1 and calculate the distance between two cells and store the minimum distance
Follow the given steps to solve the problem:
- Traverse the matrix from start to end (using two nested loops)
- For every element find the closest element which contains 1.
- To find the closest element traverse the matrix and find the minimum distance
- Fill the minimum distance in the matrix.
- Return the matrix filled with the distance values as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define N 3
#define M 4
using namespace std;
void printDistance( int mat[N][M])
{
int ans[N][M];
for ( int i = 0; i < N; i++)
for ( int j = 0; j < M; j++)
ans[i][j] = INT_MAX;
for ( int i = 0; i < N; i++)
for ( int j = 0; j < M; j++) {
for ( int k = 0; k < N; k++)
for ( int l = 0; l < M; l++) {
if (mat[k][l] == 1)
ans[i][j]
= min(ans[i][j],
abs (i - k) + abs (j - l));
}
}
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++)
cout << ans[i][j] << " " ;
cout << endl;
}
}
int main()
{
int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 };
printDistance(mat);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int N = 3 ;
static int M = 4 ;
static void printDistance( int mat[][])
{
int ans[][] = new int [N][M];
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < M; j++)
ans[i][j] = Integer.MAX_VALUE;
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < M; j++) {
for ( int k = 0 ; k < N; k++)
for ( int l = 0 ; l < M; l++) {
if (mat[k][l] == 1 )
ans[i][j] = Math.min(
ans[i][j],
Math.abs(i - k)
+ Math.abs(j - l));
}
}
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < M; j++)
System.out.print(ans[i][j] + " " );
System.out.println();
}
}
public static void main(String[] args)
{
int mat[][] = { { 0 , 0 , 0 , 1 },
{ 0 , 0 , 1 , 1 },
{ 0 , 1 , 1 , 0 } };
printDistance(mat);
}
}
|
Python3
def printDistance(mat):
global N, M
ans = [[ None ] * M for i in range (N)]
for i in range (N):
for j in range (M):
ans[i][j] = 999999999999
for i in range (N):
for j in range (M):
for k in range (N):
for l in range (M):
if (mat[k][l] = = 1 ):
ans[i][j] = min (ans[i][j],
abs (i - k) + abs (j - l))
for i in range (N):
for j in range (M):
print (ans[i][j], end = " " )
print ()
if __name__ = = '__main__' :
N = 3
M = 4
mat = [[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 1 , 1 ],
[ 0 , 1 , 1 , 0 ]]
printDistance(mat)
|
C#
using System;
class GFG {
static int N = 3;
static int M = 4;
static void printDistance( int [, ] mat)
{
int [, ] ans = new int [N, M];
for ( int i = 0; i < N; i++)
for ( int j = 0; j < M; j++)
ans[i, j] = int .MaxValue;
for ( int i = 0; i < N; i++)
for ( int j = 0; j < M; j++) {
for ( int k = 0; k < N; k++)
for ( int l = 0; l < M; l++) {
if (mat[k, l] == 1)
ans[i, j] = Math.Min(
ans[i, j],
Math.Abs(i - k)
+ Math.Abs(j - l));
}
}
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++)
Console.Write(ans[i, j] + " " );
Console.WriteLine();
}
}
public static void Main()
{
int [, ] mat = { { 0, 0, 0, 1 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 0 } };
printDistance(mat);
}
}
|
PHP
<?php
$N = 3;
$M = 4;
function printDistance( $mat )
{
global $N , $M ;
$ans = array ( array ());
for ( $i = 0; $i < $N ; $i ++)
for ( $j = 0; $j < $M ; $j ++)
$ans [ $i ][ $j ] = PHP_INT_MAX;
for ( $i = 0; $i < $N ; $i ++)
for ( $j = 0; $j < $M ; $j ++)
{
for ( $k = 0; $k < $N ; $k ++)
for ( $l = 0; $l < $M ; $l ++)
{
if ( $mat [ $k ][ $l ] == 1)
$ans [ $i ][ $j ] = min( $ans [ $i ][ $j ],
abs ( $i - $k ) + abs ( $j - $l ));
}
}
for ( $i = 0; $i < $N ; $i ++)
{
for ( $j = 0; $j < $M ; $j ++)
echo $ans [ $i ][ $j ] , " " ;
echo "\n" ;
}
}
$mat = array ( array (0, 0, 0, 1),
array (0, 0, 1, 1),
array (0, 1, 1, 0));
printDistance( $mat );
?>
|
Javascript
<script>
let N = 3;
let M = 4;
function printDistance(mat)
{
let ans= new Array(N);
for (let i=0;i<N;i++)
{
ans[i]= new Array(M);
for (let j = 0; j < M; j++)
{
ans[i][j] = Number.MAX_VALUE;
}
}
for (let i = 0; i < N; i++)
for (let j = 0; j < M; j++)
{
for (let k = 0; k < N; k++)
for (let l = 0; l < M; l++)
{
if (mat[k][l] == 1)
ans[i][j] =
Math.min(ans[i][j],
Math.abs(i-k)
+ Math.abs(j-l));
}
}
for (let i = 0; i < N; i++)
{
for (let j = 0; j < M; j++)
document.write( ans[i][j] + " " );
document.write( "<br>" );
}
}
let mat = [[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]]
printDistance(mat);
</script>
|
Output
3 2 1 0
2 1 0 0
1 0 0 1
Time Complexity: O(N2 * M2). For every element in the matrix, the matrix is traversed and there are N*M elements.
Auxiliary Space: O(N * M)
Distance of nearest cell having 1 in a binary matrix using the queue:
To solve the problem follow the below idea:
The idea is to load the i and j coordinates of each ‘1′ in the Matrix into a Queue and then traverse all the “0” Matrix elements and compare the distance between all the 1’s from the Queue to get a minimum distance
Follow the given steps to solve the problem:
- Traverse once the Matrix and Load all 1’s i and j coordinates into the queue
- Once loaded, Traverse all the Matrix elements. If the element is “0”, then check the minimum distance by de-queuing Queue elements one by one
- Once distance for a “0” element from a “1” element is obtained, push back the 1’s coordinates back into the queue again for the next “0” element
- Determine Min distance from the individual distances for every “0” element
Below is the implementation of the above approach:
C++
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <climits>
using namespace std;
struct matrix_element
{
int row;
int col;
matrix_element( int row, int col) : row(row), col(col) {}
};
void printDistance(vector<vector< int >> arr)
{
int Row_Count = arr.size();
int Col_Count = arr[0].size();
vector<matrix_element> q;
for ( int i = 0; i < Row_Count; i++)
{
for ( int j = 0; j < Col_Count; j++)
{
if (arr[i][j] == 1)
q.emplace_back(i, j);
}
}
int vector_size = q.size();
for ( int i = 0; i < Row_Count; i++)
{
for ( int j = 0; j < Col_Count; j++)
{
int distance = 0;
int min_distance = INT_MAX;
if (arr[i][j] == 0)
{
for ( int k = 0; k < vector_size; k++)
{
matrix_element One_Pos = q[0];
q.erase(q.begin());
int One_Row = One_Pos.row;
int One_Col = One_Pos.col;
distance = abs (One_Row - i) + abs (One_Col - j);
min_distance = min(min_distance, distance);
if (min_distance == 1)
{
arr[i][j] = 1;
q.emplace_back(One_Row, One_Col);
break ;
}
q.emplace_back(One_Row, One_Col);
}
arr[i][j] = min_distance;
}
else
{
arr[i][j] = 0;
}
}
}
for ( int i = 0; i < Row_Count; i++)
{
for ( int j = 0; j < Col_Count; j++)
cout << arr[i][j] << " " ;
cout << endl;
}
}
int main()
{
vector<vector< int >> arr = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0}};
printDistance(arr);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class GFG {
static class matrix_element {
int row;
int col;
matrix_element( int row, int col)
{
this .row = row;
this .col = col;
}
}
static void printDistance( int arr[][])
{
int Row_Count = arr.length;
int Col_Count = arr[ 0 ].length;
Queue<matrix_element> q
= new LinkedList<matrix_element>();
for ( int i = 0 ; i < Row_Count; i++) {
for ( int j = 0 ; j < Col_Count; j++) {
if (arr[i][j] == 1 )
q.add( new matrix_element(i, j));
}
}
int Queue_Size = q.size();
for ( int i = 0 ; i < Row_Count; i++) {
for ( int j = 0 ; j < Col_Count; j++) {
int distance = 0 ;
int min_distance = Integer.MAX_VALUE;
if (arr[i][j] == 0 ) {
for ( int k = 0 ; k < Queue_Size; k++) {
matrix_element One_Pos = q.poll();
int One_Row = One_Pos.row;
int One_Col = One_Pos.col;
distance = Math.abs(One_Row - i)
+ Math.abs(One_Col - j);
min_distance = Math.min(
min_distance, distance);
if (min_distance == 1 ) {
arr[i][j] = 1 ;
q.add( new matrix_element(
One_Row, One_Col));
break ;
}
q.add( new matrix_element(One_Row,
One_Col));
}
arr[i][j] = min_distance;
}
else {
arr[i][j] = 0 ;
}
}
}
for ( int i = 0 ; i < Row_Count; i++) {
for ( int j = 0 ; j < Col_Count; j++)
System.out.print(arr[i][j] + " " );
System.out.println();
}
}
public static void main(String[] args)
{
int arr[][] = { { 0 , 0 , 0 , 1 },
{ 0 , 0 , 1 , 1 },
{ 0 , 1 , 1 , 0 } };
printDistance(arr);
}
}
|
Python3
import sys
class matrix_element:
def __init__( self , row, col):
self .row = row
self .col = col
def printDistance(arr):
Row_Count = len (arr)
Col_Count = len (arr[ 0 ])
q = []
for i in range (Row_Count):
for j in range (Col_Count):
if (arr[i][j] = = 1 ):
q.append(matrix_element(i, j))
Queue_Size = len (q)
for i in range (Row_Count):
for j in range (Col_Count):
distance = 0
min_distance = sys.maxsize
if (arr[i][j] = = 0 ):
for k in range (Queue_Size):
One_Pos = q[ 0 ]
q = q[ 1 :]
One_Row = One_Pos.row
One_Col = One_Pos.col
distance = abs (One_Row - i) + abs (One_Col - j)
min_distance = min (min_distance, distance)
if (min_distance = = 1 ):
arr[i][j] = 1
q.append(matrix_element(One_Row, One_Col))
break
q.append(matrix_element(One_Row, One_Col))
arr[i][j] = min_distance
else :
arr[i][j] = 0
for i in range (Row_Count):
for j in range (Col_Count):
print (arr[i][j], end = " " )
print ()
if __name__ = = '__main__' :
arr = [[ 0 , 0 , 0 , 1 ], [ 0 , 0 , 1 , 1 ], [ 0 , 1 , 1 , 0 ]]
printDistance(arr)
|
C#
using System;
using System.Collections.Generic;
class matrix_element {
public int row;
public int col;
public matrix_element( int row, int col)
{
this .row = row;
this .col = col;
}
}
class GFG {
static void printDistance( int [, ] arr)
{
int Row_Count = arr.GetLength(0);
int Col_Count = arr.GetLength(1);
List<matrix_element> q = new List<matrix_element>();
for ( int i = 0; i < Row_Count; i++) {
for ( int j = 0; j < Col_Count; j++) {
if (arr[i, j] == 1)
q.Add( new matrix_element(i, j));
}
}
int List_Size = q.Count;
for ( int i = 0; i < Row_Count; i++) {
for ( int j = 0; j < Col_Count; j++) {
int distance = 0;
int min_distance = Int32.MaxValue;
if (arr[i, j] == 0) {
for ( int k = 0; k < List_Size; k++) {
matrix_element One_Pos = q[0];
q.RemoveAt(0);
int One_Row = One_Pos.row;
int One_Col = One_Pos.col;
distance = Math.Abs(One_Row - i)
+ Math.Abs(One_Col - j);
min_distance = Math.Min(
min_distance, distance);
if (min_distance == 1) {
arr[i, j] = 1;
q.Add( new matrix_element(
One_Row, One_Col));
break ;
}
q.Add( new matrix_element(One_Row,
One_Col));
}
arr[i, j] = min_distance;
}
else {
arr[i, j] = 0;
}
}
}
for ( int i = 0; i < Row_Count; i++) {
for ( int j = 0; j < Col_Count; j++)
Console.Write(arr[i, j] + " " );
Console.WriteLine();
}
}
public static void Main( string [] args)
{
int [, ] arr = { { 0, 0, 0, 1 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 0 } };
printDistance(arr);
}
}
//// This code is contributed by phasing17
|
Javascript
<script>
class matrix_element{
constructor(row, col){
this .row = row
this .col = col
}
}
function printDistance(arr){
let Row_Count = arr.length
let Col_Count = arr[0].length
let q = []
for (let i = 0; i < Row_Count; i++){
for (let j = 0; j < Col_Count; j++){
if (arr[i][j] == 1)
q.push( new matrix_element(i, j))
}
}
let Queue_Size = q.length
for (let i = 0; i < Row_Count; i++)
{
for (let j = 0; j < Col_Count; j++)
{
let distance = 0
let min_distance = Number.MAX_VALUE
if (arr[i][j] == 0){
for (let k = 0; k < Queue_Size; k++)
{
let One_Pos = q.shift()
let One_Row = One_Pos.row
let One_Col = One_Pos.col
distance = Math.abs(One_Row - i) + Math.abs(One_Col - j)
min_distance = Math.min(min_distance, distance)
if (min_distance == 1){
arr[i][j] = 1
q.push( new matrix_element(One_Row, One_Col))
break
}
q.push( new matrix_element(One_Row,One_Col))
arr[i][j] = min_distance
}
}
else
arr[i][j] = 0
}
}
for (let i = 0; i < Row_Count; i++)
{
for (let j = 0; j < Col_Count; j++)
{
document.write(arr[i][j] , " " )
}
document.write( "</br>" )
}
}
let arr = [ [ 0, 0, 0, 1 ], [ 0, 0, 1, 1 ], [ 0, 1, 1, 0 ] ]
printDistance(arr)
</script>
|
Output
3 2 1 0
2 1 0 0
1 0 0 1
Time Complexity: O(N2 * M2)
Auxiliary Space: O(N * M)
Distance of nearest cell having 1 in a binary matrix using the BFS method:
To solve the problem follow the below idea:
The idea is to use multisource Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. Number each cell from 1 to N*M. Now, push all the nodes whose corresponding cell value is 1 in the matrix in the queue. Apply BFS using this queue to find the minimum distance of the adjacent node
Follow the given steps to solve the problem:
- Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to store position and adjacent information.
- Create an empty queue.
- Traverse all matrix elements and insert positions of all 1s in the queue.
- Now do a BFS traversal of the graph using the above-created queue.
- Run a loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its adjacent and unmarked elements.
- Update the minimum distance as the distance of the current node +1 and insert the element in the queue.
- Return the matrix containing the distances as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define MAX 500
#define N 3
#define M 4
using namespace std;
class graph {
private :
vector< int > g[MAX];
int n, m;
public :
graph( int a, int b)
{
n = a;
m = b;
}
void createGraph()
{
int k = 1;
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= m; j++) {
if (i == n) {
if (j != m) {
g[k].push_back(k + 1);
g[k + 1].push_back(k);
}
}
else if (j == m) {
g[k].push_back(k + m);
g[k + m].push_back(k);
}
else {
g[k].push_back(k + 1);
g[k + 1].push_back(k);
g[k].push_back(k + m);
g[k + m].push_back(k);
}
k++;
}
}
}
void bfs( bool visit[], int dist[], queue< int > q)
{
while (!q.empty()) {
int temp = q.front();
q.pop();
for ( int i = 0; i < g[temp].size(); i++) {
if (visit[g[temp][i]] != 1) {
dist[g[temp][i]] = min(dist[g[temp][i]],
dist[temp] + 1);
q.push(g[temp][i]);
visit[g[temp][i]] = 1;
}
}
}
}
void print( int dist[])
{
for ( int i = 1, c = 1; i <= n * m; i++, c++) {
cout << dist[i] << " " ;
if (c % m == 0)
cout << endl;
}
}
};
void findMinDistance( bool mat[N][M])
{
graph g1(N, M);
g1.createGraph();
int dist[MAX];
bool visit[MAX] = { 0 };
for ( int i = 1; i <= M * N; i++) {
dist[i] = INT_MAX;
visit[i] = 0;
}
int k = 1;
queue< int > q;
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
if (mat[i][j] == 1) {
dist[k] = 0;
visit[k] = 1;
q.push(k);
}
k++;
}
}
g1.bfs(visit, dist, q);
g1.print(dist);
}
int main()
{
bool mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 };
findMinDistance(mat);
return 0;
}
|
Java
import java.util.*;
class gfg {
static int N = 3 ;
static int M = 4 ;
static int MAX = 500 ;
static class graph {
ArrayList<ArrayList<Integer> > g;
int n, m;
graph( int a, int b)
{
g = new ArrayList<>();
n = a;
m = b;
}
void createGraph()
{
int k = 1 ;
for ( int i = 0 ; i <= MAX; i++) {
g.add( new ArrayList<>());
}
for ( int i = 1 ; i <= n; i++) {
for ( int j = 1 ; j <= m; j++) {
if (i == n) {
if (j != m) {
g.get(k).add(k + 1 );
g.get(k + 1 ).add(k);
}
}
else if (j == m) {
g.get(k).add(k + m);
g.get(k + m).add(k);
}
else {
g.get(k).add(k + 1 );
g.get(k + 1 ).add(k);
g.get(k).add(k + m);
g.get(k + m).add(k);
}
k++;
}
}
}
void bfs( boolean visit[], int dist[],
Queue<Integer> q)
{
while (!q.isEmpty()) {
int temp = q.peek();
q.remove();
for ( int i = 0 ; i < g.get(temp).size();
i++) {
if (visit[g.get(temp).get(i)] != true ) {
dist[g.get(temp).get(i)] = Math.min(
dist[g.get(temp).get(i)],
dist[temp] + 1 );
q.add(g.get(temp).get(i));
visit[g.get(temp).get(i)] = true ;
}
}
}
}
void print( int dist[])
{
for ( int i = 1 , c = 1 ; i <= n * m; i++, c++) {
System.out.print(dist[i] + " " );
if (c % m == 0 )
System.out.println();
}
}
};
static void findMinDistance( boolean mat[][])
{
graph g1 = new graph(N, M);
g1.createGraph();
int dist[] = new int [MAX];
boolean visit[] = new boolean [MAX];
for ( int i = 1 ; i <= M * N; i++) {
dist[i] = Integer.MAX_VALUE;
visit[i] = false ;
}
int k = 1 ;
Queue<Integer> q = new ArrayDeque<>();
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < M; j++) {
if (mat[i][j]) {
dist[k] = 0 ;
visit[k] = true ;
q.add(k);
}
k++;
}
}
g1.bfs(visit, dist, q);
g1.print(dist);
}
public static void main(String[] args)
{
int matrix[][] = { { 0 , 0 , 0 , 1 },
{ 0 , 0 , 1 , 1 },
{ 0 , 1 , 1 , 0 } };
boolean [][] mat = new boolean [N][M];
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < M; j++) {
if (matrix[i][j] == 1 )
mat[i][j] = true ;
}
}
findMinDistance(mat);
}
}
|
Python3
from collections import deque
MAX = 500
N = 3
M = 4
g = [[] for i in range ( MAX )]
n, m = 0 , 0
def createGraph():
global g, n, m
k = 1
for i in range ( 1 , n + 1 ):
for j in range ( 1 , m + 1 ):
if (i = = n):
if (j ! = m):
g[k].append(k + 1 )
g[k + 1 ].append(k)
elif (j = = m):
g[k].append(k + m)
g[k + m].append(k)
else :
g[k].append(k + 1 )
g[k + 1 ].append(k)
g[k].append(k + m)
g[k + m].append(k)
k + = 1
def bfs(visit, dist, q):
global g
while ( len (q) > 0 ):
temp = q.popleft()
for i in g[temp]:
if (visit[i] ! = 1 ):
dist[i] = min (dist[i], dist[temp] + 1 )
q.append(i)
visit[i] = 1
return dist
def prt(dist):
c = 1
for i in range ( 1 , n * m + 1 ):
print (dist[i], end = " " )
if (c % m = = 0 ):
print ()
c + = 1
def findMinDistance(mat):
global g, n, m
n, m = N, M
createGraph()
dist = [ 0 ] * MAX
visit = [ 0 ] * MAX
for i in range ( 1 , M * N + 1 ):
dist[i] = 10 * * 9
visit[i] = 0
k = 1
q = deque()
for i in range (N):
for j in range (M):
if (mat[i][j] = = 1 ):
dist[k] = 0
visit[k] = 1
q.append(k)
k + = 1
dist = bfs(visit, dist, q)
prt(dist)
if __name__ = = '__main__' :
mat = [[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 1 , 1 ],
[ 0 , 1 , 1 , 0 ]]
findMinDistance(mat)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class gfg {
static int N = 3;
static int M = 4;
static int MAX = 500;
public class graph {
public List<List< int > > g;
public int n, m;
public graph( int a, int b)
{
g = new List<List< int > >();
n = a;
m = b;
}
public void createGraph()
{
int k = 1;
for ( int i = 0; i <= MAX; i++) {
g.Add( new List< int >());
}
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j <= m; j++) {
if (i == n) {
if (j != m) {
g[k].Add(k + 1);
g[k + 1].Add(k);
}
}
else if (j == m) {
g[k].Add(k + m);
g[k + m].Add(k);
}
else {
g[k].Add(k + 1);
g[k + 1].Add(k);
g[k].Add(k + m);
g[k + m].Add(k);
}
k++;
}
}
}
public void bfs( bool [] visit, int [] dist,
Queue< int > q)
{
while (q.Count != 0) {
int temp = q.Peek();
q.Dequeue();
for ( int i = 0; i < g[temp].Count; i++) {
if (visit[g[temp][i]] != true ) {
dist[g[temp][i]]
= Math.Min(dist[g[temp][i]],
dist[temp] + 1);
q.Enqueue(g[temp][i]);
visit[g[temp][i]] = true ;
}
}
}
}
public void print( int [] dist)
{
for ( int i = 1, c = 1; i <= n * m; i++, c++) {
Console.Write(dist[i] + " " );
if (c % m == 0)
Console.WriteLine();
}
}
};
static void findMinDistance( bool [, ] mat)
{
graph g1 = new graph(N, M);
g1.createGraph();
int [] dist = new int [MAX];
bool [] visit = new bool [MAX];
for ( int i = 1; i <= M * N; i++) {
dist[i] = Int32.MaxValue;
visit[i] = false ;
}
int k = 1;
Queue< int > q = new Queue< int >();
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
if (mat[i, j]) {
dist[k] = 0;
visit[k] = true ;
q.Enqueue(k);
}
k++;
}
}
g1.bfs(visit, dist, q);
g1.print(dist);
}
public static void Main( string [] args)
{
int [, ] matrix = { { 0, 0, 0, 1 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 0 } };
bool [, ] mat = new bool [N, M];
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
if (matrix[i, j] == 1)
mat[i, j] = true ;
}
}
findMinDistance(mat);
}
}
|
Javascript
let MAX = 500;
let N = 3;
let M = 4;
let dist, visit;
let g = new Array(MAX);
for ( var i = 0; i < MAX; i++)
g[i] = []
let n = 0, m = 0;
function createGraph() {
let k = 1;
for (let i = 1; i <= n + 1; i++) {
for (let j = 1; j <= m + 1; j++) {
if (i === n) {
if (j !== m) {
g[k].push(k + 1);
g[k + 1].push(k);
}
}
else if (j === m) {
g[k].push(k + m);
g[k + m].push(k);
}
else {
g[k].push(k + 1);
g[k + 1].push(k);
g[k].push(k + m);
g[k + m].push(k);
}
k += 1;
}
}
}
function bfs(visit, dist, q) {
while (q.length > 0) {
let temp = q.shift();
for (let i of g[temp]) {
if (visit[i] !== 1) {
dist[i] = Math.min(dist[i], dist[temp] + 1);
q.push(i);
visit[i] = 1;
}
}
}
return dist;
}
function prt(dist) {
let c = 1;
for (let i = 1; i <= n * m + 1; i++) {
process.stdout.write(dist[i] + " " );
if (c % m === 0) {
console.log();
}
c += 1;
}
}
function findMinDistance(mat) {
n = N;
m = M;
createGraph();
dist = new Array(MAX).fill(0);
visit = new Array(MAX).fill(0);
for ( var i = 1; i <= M * N; i++)
{
dist[i] = 10**9
visit[i] = 0
}
let k = 1
let q = []
for ( var i = 0; i < N; i++)
{
for ( var j = 0; j < M; j++)
{
if (mat[i][j] == 1)
{
dist[k] = 0
visit[k] = 1
q.push(k)
}
k += 1
}
}
dist = bfs(visit, dist, q)
prt(dist)
}
let mat = [[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]]
findMinDistance(mat)
|
Output
3 2 1 0
2 1 0 0
1 0 0 1
Time Complexity: O(N*M). In BFS traversal every element is traversed only once so the time Complexity is O(M*N).
Space Complexity: O(M*N). To store every element in the matrix O(M*N) space is required.
Distance of nearest cell having 1 in a binary matrix using the BFS method using same grid (given matrix):
To solve the problem follow the below idea:
The idea is to use multisource Breadth-First Search.First we need to mark all the initial 1s present in given matrix
by storing there index(i,j) in queue<pair<int,int>>,we also know that these 1s are the starting point (meaning
from their index distance will be calculated.) so we make all these 1s to 0, then we can also say that all the 0s
present initially in matrix will soon replaced by distance so we assume the distance as infinite,so we make all 0s
present in initial matrix as INT_MAX.
eg:
n = 3 ,m=4 (? = INT_MAX) _____________________________________
0 1 0 0 ? 0 ? ? | | | | |
1 1 0 0 -----> 0 0 ? ? queue<int,int> | {0,1} |{1,1} | {2,2} | {2,3} |
0 0 1 1 ? ? 0 0 |_______|______|_______|_______|__________
Follow the given steps to solve the problem:
NOTE: grid[ i ][ j ]==0 means this is the starting point and grid[ i ][ j ]==INT_MAX is imaginary distance. this concept will be used for visited and unvisited purposes. Only grid[ i ][ j ]==INT_MAX will be treated as unvisited, everything else will be treated as visited.
- Create a queue<pair<int,int>> q
- Traverse the matrix and do two tasks if (grid[i][j]==1) { q.push( { i , j } ); grid[ i ][ j ] = 0; } else { grid[ i ][ j ] = INT_MAX; }
- Now do a BFS traversal of the graph using the above-created queue.
- Run while loop till the size of the queue is greater than 0 then extract the front node of the queue and remove it and insert all its valid adjacent nodes if (grid[ i ][ j ] = INT_MAX) // it means this node is unvisited till now.
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector< int > >
printDistance(vector<vector< int > >& grid)
{
int n = grid.size(),
m
= grid[0]
.size();
queue<pair< int , int > >
q;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (grid[i][j]) {
q.push({ i, j });
grid[i][j]
= 0;
}
else
grid[i][j]
= INT_MAX;
}
}
int row[4] = { -1, 1, 0, 0 }, col[4] = {
0, 0, -1, 1
};
while (!q.empty()) {
auto top = q.front();
q.pop();
int x = top.first
,
y = top.second
,
time = grid[x][y];
for ( int i = 0; i < 4; i++) {
int newx = x + row[i], newy = y + col[i];
if (newx >= 0 && newx < n && newy >= 0
&& newy < m
&& grid[newx][newy]
== INT_MAX) {
grid[newx][newy]
= time + 1;
q.push(
{ newx,
newy });
}
}
}
return grid;
}
int main()
{
vector<vector< int > > grid = { { 0, 1, 0, 0 },
{ 1, 1, 0, 0 },
{ 0, 0, 1, 1 } };
printDistance(grid);
for ( auto row : grid) {
for ( auto eachcal : row) {
cout << eachcal << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.*;
public class GFG {
static class pair {
int first, second;
pair( int f, int s)
{
first = f;
second = s;
}
}
static int [][] printDistance( int [][] grid)
{
int n = grid.length, m = grid[ 0 ].length;
Queue<pair> q = new ArrayDeque<>();
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < m; j++) {
if (grid[i][j] != 0 ) {
q.add( new pair(i, j));
grid[i][j] = 0 ;
}
else
grid[i][j]
= Integer
.MAX_VALUE;
}
}
int row[] = { - 1 , 1 , 0 , 0 }, col[] = {
0 , 0 , - 1 , 1
};
while (q.size() != 0 ) {
pair top = q.peek();
q.remove();
int x = top.first
,
y = top.second
,
time
= grid[x][y];
for ( int i = 0 ; i < 4 ; i++) {
int newx = x + row[i], newy = y + col[i];
if (newx >= 0 && newx < n && newy >= 0
&& newy < m
&& grid[newx][newy]
== Integer
.MAX_VALUE) {
grid[newx][newy]
= time
+ 1 ;
q.add( new pair(newx, newy));
}
}
}
return grid;
}
public static void main(String[] args)
{
int [][] grid = { { 0 , 1 , 0 , 0 },
{ 1 , 1 , 0 , 0 },
{ 0 , 0 , 1 , 1 } };
grid = printDistance(grid);
for ( int [] row : grid) {
for ( int eachcal : row) {
System.out.print(eachcal + " " );
}
System.out.println();
}
}
}
|
Python3
def printDistance(grid):
n = len (grid)
m = len (grid[ 0 ])
q = []
for i in range (n):
for j in range (m):
if grid[i][j]:
q.append([i, j])
grid[i][j] = 0
else :
grid[i][j] = float ( "inf" )
row = [ - 1 , 1 , 0 , 0 ]
col = [ 0 , 0 , - 1 , 1 ]
while len (q):
top = q.pop( 0 )
x = top[ 0 ]
y = top[ 1 ]
time = grid[x][y]
for i in range ( 4 ):
newx = x + row[i]
newy = y + col[i]
if newx > = 0 and newx < n and newy > = 0 and newy < m and grid[newx][newy] = = float ( "inf" ):
grid[newx][newy] = time + 1
q.append([newx, newy])
return grid
grid = [[ 0 , 1 , 0 , 0 ], [ 1 , 1 , 0 , 0 ], [ 0 , 0 , 1 , 1 ]]
print ( * printDistance(grid), sep = '\n' )
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
public class pair {
public int first, second;
public pair( int f, int s)
{
first = f;
second = s;
}
}
static List<List< int > >
printDistance(List<List< int > > grid)
{
int n = grid.Count, m = grid[0].Count;
Queue<pair> q = new Queue<pair>();
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (grid[i][j] != 0) {
q.Enqueue( new pair(i, j));
grid[i][j] = 0;
}
else
grid[i][j] = Int32.MaxValue;
}
}
int [] row = { -1, 1, 0, 0 }, col = {
0, 0, -1, 1
};
while (q.Count != 0) {
pair top = q.Peek();
q.Dequeue();
int x = top.first
,
y = top.second
,
time
= grid[x][y];
for ( int i = 0; i < 4; i++) {
int newx = x + row[i], newy = y + col[i];
if (newx >= 0 && newx < n && newy >= 0
&& newy < m
&& grid[newx][newy]
== Int32.MaxValue) {
grid[newx][newy]
= time
+ 1;
q.Enqueue( new pair(newx, newy));
}
}
}
return grid;
}
public static void Main( string [] args)
{
List<List< int > > grid = new List<List< int > >{
new List< int >{ 0, 1, 0, 0 },
new List< int >{ 1, 1, 0, 0 },
new List< int >{ 0, 0, 1, 1 }
};
grid = printDistance(grid);
foreach (List< int > row in grid)
{
foreach ( int eachcal in row)
{
Console.Write(eachcal + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
const printDistance = (grid) => {
let n = grid.length,
m = grid[0].length;
let q = new Array();
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (grid[i][j]) {
q.push([i, j]);
grid[i][j] = 0;
}
else
grid[i][j] = Number.MAX_VALUE;
}
}
let row = [-1, 1, 0, 0], col = [0, 0, -1, 1];
while (q.length) {
let top = q.shift();
let x = top[0], y = top[1], time = grid[x][y];
for (let i = 0; i < 4; i++) {
let newx = x + row[i], newy = y + col[i];
if (newx >= 0 && newx < n && newy >= 0
&& newy < m
&& grid[newx][newy] === Number.MAX_VALUE) {
grid[newx][newy] = time + 1;
q.push([newx, newy]);
}
}
}
return grid;
}
let grid = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1]];
console.log(printDistance(grid).join( "\n" ));
|
Output
1 0 1 2
0 0 1 1
1 1 0 0
Time Complexity: O(N*M).
Auxiliary Space: O(M*N)
Share your thoughts in the comments
Please Login to comment...