Nearest 1 in a binary matrix - GeeksforGeeks

18 Apr, 2022
Given a binary matrix of order m*n, the task is to find the distance of nearest 1 for each 0 in the matrix and print final distance matrix. From any cell (i,j), we can move only in four directions up, down, left and right. Note : Distance from one cell to immediate another cell is always incremented by 1.Examples:  
Input : m = 3, n = 4
        mat[m][n] = {{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
 
A simple solution for this problem is to for each 0 in the matrix recursively check the nearest 1 in the matrix.An efficient solution solution for this problem is to use BFS. Here is the algorithm to solve this problem :  
Take distance matrix dist[m][n] and initialize it with INT_MAX.
Now traverse the matrix and make_pair(i,j) of indices of cell (i, j) having value ‘1’ and push this pair into queue and update dist[i][j] = 0 because distance of ‘1’ from itself will be always 0.
Now pop elements from queue one by one until it gets empty and call BFS on it.
Here we need to find the distance of nearest one and we are calling BFS for the cells having ‘1’, so whenever we take adjacent of popped element from queue, we try to minimize the distance by putting condition if (dist[i][j]+1) < dist[ADCi][ADCj]. Then we update the distance of adjacent element in the distance matrix and push this adjacent in the queue to complete the BFS traversal and filling the complete distance matrix.
After completing the BFS traversal each cell of distance matrix will contain the distance of nearest ‘1’.
 
C++
Python3
// C++ program to find the minimum distance from a// "1" in binary matrix.#include<bits/stdc++.h>using namespace std;const int MAX = 1000; // distance matrix which stores the distance of// nearest '1'int dist[MAX][MAX]; // Function to find the nearest '1'void nearestOne(int mat[][MAX], int m, int n){    // two array when respective values of newx and    // newy are added to (i,j) it gives up, down,    // left or right adjacent of (i,j) cell    int newx[] = {-1, 0, 1, 0};    int newy[] = {0, -1, 0, 1};     // queue of pairs to store nodes for bfs    queue< pair<int,int> > q;     // traverse matrix and make pair of indices of    // cell (i,j) having value '1' and push them    // in queue    for (int i=0; i<m; i++)    {        for (int j=0; j<n; j++)        {            dist[i][j] = INT_MAX;             if (mat[i][j] == 1)            {                // distance of '1' from itself is always 0                dist[i][j] = 0;                 // make pair and push it in queue                q.push(make_pair(i, j));            }        }    }     // now do bfs traversal    // pop element from queue one by one until it gets empty    // pair element to hold the currently popped element    pair<int ,int> poped;    while (!q.empty())    {        poped = q.front();        q.pop();         // coordinate of currently popped node        int x = poped.first;        int y = poped.second;         // now check for all adjacent of popped element        for (int i=0; i<4; i++)        {            int adjx = x + newx[i];            int adjy = y + newy[i];             // if new coordinates are within boundary and            // we can minimize the distance of adjacent            // then update the distance of adjacent in            // distance matrix and push this adjacent            // element in queue for further bfs            if (adjx>=0 && adjx<m && adjy>=0 && adjy<n &&                    dist[adjx][adjy] > dist[x][y] + 1)            {                // update distance                dist[adjx][adjy] = dist[x][y] + 1;                q.push(make_pair(adjx,adjy));            }        }    }} // Driver program to run the caseint main(){    int m = 3, n = 4;    int mat[][MAX] = {{0, 0, 0, 1},        {0, 0, 1, 1},        {0, 1, 1, 0}    };      // Fills values in dist[][]    nearestOne(mat, m, n);     // print distance matrix    for (int i=0; i<m; i++)    {        for (int j=0; j<n; j++)            cout << dist[i][j] << " ";        cout << endl;    }    return 0;}
# Python3 program to find the minimum distance from a# "1" in binary matrix.MAX = 1000INT_MAX = (2**32) # distance matrix which stores the distance of# nearest '1'dist = [[0 for i in range(MAX)] for j in range(MAX)] # Function to find the nearest '1'def nearestOne(mat, m, n):         # two array when respective values of newx and    # newy are added to (i,j) it gives up, down,    # left or right adjacent of (i,j) cell    newx = [-1, 0, 1, 0]    newy = [0, -1, 0, 1]         # queue of pairs to store nodes for bfs    q = []         # traverse matrix and make pair of indices of    # cell (i,j) having value '1' and push them    # in queue    for i in range(m):        for j in range(n):            dist[i][j] = INT_MAX            if (mat[i][j] == 1):                                 # distance of '1' from itself is always 0                dist[i][j] = 0                                 # make pair and push it in queue                q.append([i, j])         # now do bfs traversal    # pop element from queue one by one until it gets empty    # pair element to hold the currently popped element    poped = []    while (len(q)):        poped = q[0]        q.pop(0)                 # coordinate of currently popped node        x = poped[0]        y = poped[1]                 # now check for all adjacent of popped element        for i in range(4):                         adjx = x + newx[i]            adjy = y + newy[i]                         # if new coordinates are within boundary and            # we can minimize the distance of adjacent            # then update the distance of adjacent in            # distance matrix and push this adjacent            # element in queue for further bfs            if (adjx >= 0 and adjx < m and adjy >= 0 and                adjy < n and dist[adjx][adjy] > dist[x][y] + 1):                                 # update distance                dist[adjx][adjy] = dist[x][y] + 1                q.append([adjx, adjy]) # Driver codem = 3n = 4mat= [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]] # Fills values in dist[][]nearestOne(mat, m, n) # print distance matrixfor i in range(m):    for j in range(n):        print(dist[i][j], end=" ")    print() # This code is contributed by shubhamsingh10
Output:  
3 2 1 0
2 1 0 0
1 0 0 1
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
Akanksha_Rai
ManasChhabra2
SHUBHAMSINGH10
surinderdawra388
BFS
Matrix
Matrix
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Sudoku | Backtracking-7
Program to multiply two matrices
Count all possible paths from top left to bottom right of a mXn matrix
Min Cost Path | DP-6
The Celebrity Problem
Python program to multiply two matrices
Printing all solutions in N-Queen Problem
Program to find transpose of a matrix
Multiplication of two Matrices in Single line using Numpy in Python