Given a binary matrix of N x M, containing at least a value 1. The task is to find the distance of 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.
Method 1: This method uses a simple brute force approach to arrive at the solution.
- Approach: 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 calculates the distance between two cells and store the minimum distance.
- Algorithm :
- 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.
-
Implementation:
C++
// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define N 3#define M 4usingnamespacestd;// Print the distance of nearest cell// having 1 for each cell.voidprintDistance(intmat[N][M]){intans[N][M];// Initialize the answer matrix with INT_MAX.for(inti = 0; i < N; i++)for(intj = 0; j < M; j++)ans[i][j] = INT_MAX;// For each cellfor(inti = 0; i < N; i++)for(intj = 0; j < M; j++){// Traversing the whole matrix// to find the minimum distance.for(intk = 0; k < N; k++)for(intl = 0; l < M; l++){// If cell contain 1, check// for minimum distance.if(mat[k][l] == 1)ans[i][j] = min(ans[i][j],abs(i-k) +abs(j-l));}}// Printing the answer.for(inti = 0; i < N; i++){for(intj = 0; j < M; j++)cout << ans[i][j] <<" ";cout << endl;}}// Driven Programintmain(){intmat[N][M] ={0, 0, 0, 1,0, 0, 1, 1,0, 1, 1, 0};printDistance(mat);return0;}chevron_rightfilter_noneJava
// Java program to find distance of nearest// cell having 1 in a binary matrix.importjava.io.*;classGFG {staticintN =3;staticintM =4;// Print the distance of nearest cell// having 1 for each cell.staticvoidprintDistance(intmat[][]){intans[][] =newint[N][M];// Initialize the answer matrix with INT_MAX.for(inti =0; i < N; i++)for(intj =0; j < M; j++)ans[i][j] = Integer.MAX_VALUE;// For each cellfor(inti =0; i < N; i++)for(intj =0; j < M; j++){// Traversing the whole matrix// to find the minimum distance.for(intk =0; k < N; k++)for(intl =0; l < M; l++){// If cell contain 1, check// for minimum distance.if(mat[k][l] ==1)ans[i][j] =Math.min(ans[i][j],Math.abs(i-k)+ Math.abs(j-l));}}// Printing the answer.for(inti =0; i < N; i++){for(intj =0; j < M; j++)System.out.print( ans[i][j] +" ");System.out.println();}}// Driven Programpublicstaticvoidmain (String[] args){intmat[][] = { {0,0,0,1},{0,0,1,1},{0,1,1,0} };printDistance(mat);}}// This code is contributed by anuj_67.chevron_rightfilter_nonePython3
# Python3 program to find distance of# nearest cell having 1 in a binary matrix.# Prthe distance of nearest cell# having 1 for each cell.defprintDistance(mat):globalN, Mans=[[None]*Mforiinrange(N)]# Initialize the answer matrix# with INT_MAX.foriinrange(N):forjinrange(M):ans[i][j]=999999999999# For each cellforiinrange(N):forjinrange(M):# Traversing the whole matrix# to find the minimum distance.forkinrange(N):forlinrange(M):# If cell contain 1, check# for minimum distance.if(mat[k][l]==1):ans[i][j]=min(ans[i][j],abs(i-k)+abs(j-l))# Printing the answer.foriinrange(N):forjinrange(M):print(ans[i][j], end=" ")print()# Driver CodeN=3M=4mat=[[0,0,0,1],[0,0,1,1],[0,1,1,0]]printDistance(mat)# This code is contributed by PranchalKchevron_rightfilter_noneC#
// C# program to find the distance of nearest// cell having 1 in a binary matrix.usingSystem;classGFG {staticintN = 3;staticintM = 4;// Print the distance of nearest cell// having 1 for each cell.staticvoidprintDistance(int[,]mat){int[,]ans =newint[N,M];// Initialise the answer matrix with int.MaxValue.for(inti = 0; i < N; i++)for(intj = 0; j < M; j++)ans[i,j] =int.MaxValue;// For each cellfor(inti = 0; i < N; i++)for(intj = 0; j < M; j++){// Traversing thewhole matrix// to find the minimum distance.for(intk = 0; k < N; k++)for(intl = 0; l < M; l++){// If cell contain 1, check// for minimum distance.if(mat[k,l] == 1)ans[i,j] =Math.Min(ans[i,j],Math.Abs(i-k)+ Math.Abs(j-l));}}// Printing the answer.for(inti = 0; i < N; i++){for(intj = 0; j < M; j++)Console.Write( ans[i,j] +" ");Console.WriteLine();}}// Driven ProgrampublicstaticvoidMain (){int[,]mat = { {0, 0, 0, 1},{0, 0, 1, 1},{0, 1, 1, 0} };printDistance(mat);}}// This code is contributed by anuj_67.chevron_rightfilter_nonePHP
<?php// PHP program to find distance of nearest// cell having 1 in a binary matrix.$N= 3;$M= 4;// Print the distance of nearest cell// having 1 for each cell.functionprintDistance($mat){global$N,$M;$ans=array(array());// Initialize the answer// matrix with INT_MAX.for($i= 0;$i<$N;$i++)for($j= 0;$j<$M;$j++)$ans[$i][$j] = PHP_INT_MAX;// For each cellfor($i= 0;$i<$N;$i++)for($j= 0;$j<$M;$j++){// Traversing the whole matrix// to find the minimum distance.for($k= 0;$k<$N;$k++)for($l= 0;$l<$M;$l++){// If cell contain 1, check// for minimum distance.if($mat[$k][$l] == 1)$ans[$i][$j] = min($ans[$i][$j],abs($i-$k) +abs($j-$l));}}// Printing the answer.for($i= 0;$i<$N;$i++){for($j= 0;$j<$M;$j++)echo$ans[$i][$j] ," ";echo"\n";}}// Driver Code$mat=array(array(0, 0, 0, 1),array(0, 0, 1, 1),array(0, 1, 1, 0));printDistance($mat);// This code is contributed by anuj_67.?>chevron_rightfilter_none
Output:3 2 1 0 2 1 0 0 1 0 0 1
-
Complexity Analysis:- Time Complexity: O(N2*M2).
For every element in the matrix, the matrix is traversed and there are N*M elements So the time complexity is O(N2*M2). - Space Complexity: O(1).
No extra space is required.
- Time Complexity: O(N2*M2).
Method 2: This method uses the BFS or breadth-first search technique to arrive at the solution.
- Approach: 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 node 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.
- Algorithm:
- 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 queue.
- Now do a BFS traversal of graph using 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 distance of current node +1 and insert the element in the queue.
-
Implementation:
// C++ program to find distance of nearest// cell having 1 in a binary matrix.#include<bits/stdc++.h>#define MAX 500#define N 3#define M 4usingnamespacestd;// Making a class of graph with bfs function.classgraph{private:vector<int> g[MAX];intn,m;public:graph(inta,intb){n = a;m = b;}// Function to create graph with N*M nodes// considering each cell as a node and each// boundary as an edge.voidcreateGraph(){intk = 1;// A number to be assigned to a cellfor(inti = 1; i <= n; i++){for(intj = 1; j <= m; j++){// If last row, then add edge on right side.if(i == n){// If not bottom right cell.if(j != m){g[k].push_back(k+1);g[k+1].push_back(k);}}// If last column, then add edge toward down.elseif(j == m){g[k].push_back(k+m);g[k+m].push_back(k);}// Else makes an edge in all four directions.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++;}}}// BFS function to find minimum distancevoidbfs(boolvisit[],intdist[], queue<int> q){while(!q.empty()){inttemp = q.front();q.pop();for(inti = 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;}}}}// Printing the solution.voidprint(intdist[]){for(inti = 1, c = 1; i <= n*m; i++, c++){cout << dist[i] <<" ";if(c%m == 0)cout << endl;}}};// Find minimum distancevoidfindMinDistance(boolmat[N][M]){// Creating a graph with nodes values assigned// from 1 to N x M and matrix adjacent.graph g1(N, M);g1.createGraph();// To store minimum distanceintdist[MAX];// To mark each node as visited or not in BFSboolvisit[MAX] = { 0 };// Initialising the value of distance and visit.for(inti = 1; i <= M*N; i++){dist[i] = INT_MAX;visit[i] = 0;}// Inserting nodes whose value in matrix// is 1 in the queue.intk = 1;queue<int> q;for(inti = 0; i < N; i++){for(intj = 0; j < M; j++){if(mat[i][j] == 1){dist[k] = 0;visit[k] = 1;q.push(k);}k++;}}// Calling for Bfs with given Queue.g1.bfs(visit, dist, q);// Printing the solution.g1.print(dist);}// Driven Programintmain(){boolmat[N][M] ={0, 0, 0, 1,0, 0, 1, 1,0, 1, 1, 0};findMinDistance(mat);return0;}chevron_rightfilter_noneOutput :
3 2 1 0 2 1 0 0 1 0 0 1
-
Complexity Analysis:
- Time Complexity: O(N*M).
In BFS traversal every element is traversed only once so time Complexity is O(M*N). - Space Complexity: O(M*N).
To store every element in the matrix O(M*N) space is required.
- Time Complexity: O(N*M).
This article is contributed by Anuj Chauhan. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

