# Nearest 1 in a binary matrix

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++

`// 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 adjancent 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 case ` `int` `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; ` `} ` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program to find the minimum distance from a ` `# "1" in binary matrix. ` `MAX` `=` `1000` `INT_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 adjancent 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 code ` `m ` `=` `3` `n ` `=` `4` `mat` `=` `[[` `0` `, ` `0` `, ` `0` `, ` `1` `], [` `0` `, ` `0` `, ` `1` `, ` `1` `], [` `0` `, ` `1` `, ` `1` `, ` `0` `]] ` ` ` `# Fills values in dist[][] ` `nearestOne(mat, m, n) ` ` ` `# prdistance matrix ` `for` `i ` `in` `range` `(m): ` ` ` `for` `j ` `in` `range` `(n): ` ` ` `print` `(dist[i][j], end` `=` `" "` `) ` ` ` `print` `() ` ` ` `# This code is conributed by shubhamsingh10 ` |

*chevron_right*

*filter_none*

**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 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.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

## Recommended Posts:

- Distance of nearest cell having 1 in a binary matrix
- Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix
- Program to check if a matrix is Binary matrix or not
- Counting sets of 1s and 0s in a binary matrix
- Count all 0s which are blocked by 1s in binary matrix
- Unique cells in a binary matrix
- Construct Ancestor Matrix from a Given Binary Tree
- Total coverage of all zeros in a binary matrix
- Maximum decimal value path in a binary matrix
- Maximum size rectangle binary sub-matrix with all 1s
- Find if there is a rectangle in binary matrix with corners as 1
- Minimum steps to get 1 at the center of a binary matrix
- Find duplicate rows in a binary matrix
- Maximize the binary matrix by filpping submatrix once
- Construct Binary Tree from Ancestor Matrix | Top Down Approach