Nearest 1 in a binary matrix
Last Updated :
18 Mar, 2025
Given a binary grid of n*m. Find the distance of the nearest 1 in the grid 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. There should be at least one 1 in the grid.
Examples:
Input: grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]]
Output: [[1,0,0,1], [0,0,1,1], [1,1,0,0]]
Explanation: The grid is-
0 1 1 0
1 1 0 0
0 0 1 1
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. The following image shows distances to the nearest 1s.

Input: grid = [[1,0,1], [1,1,0], [1,0,0]]
Output: [[0,1,0], [0,0,1], [0,1,2]]
Explanation: The grid is-
1 0 1
1 1 0
1 0 0
The following image shows distances to the nearest 1s.

[Naive Approach] - O(n^2 * m^2) Time and O(n * m) Space
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.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
vector<vector<int>> nearest(vector<vector<int>> &grid) {
int n = grid.size();
int m = grid[0].size();
// to store the answer
vector<vector<int>> ans(n, vector<int>(m, INT_MAX));
// visit each cell of the grid
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
// if the cell has 1,
// then the distance is 0
if(grid[i][j] == 1) {
ans[i][j] = 0;
continue;
}
// iterate over all the cells
// and find the distance of the nearest 1
for(int k = 0; k<n; k++) {
for(int l = 0; l<m; l++) {
if(grid[k][l] == 1) {
ans[i][j] = min(ans[i][j], abs(i-k) + abs(j-l));
}
}
}
}
}
return ans;
}
int main() {
vector<vector<int>> grid = {{0,1,1,0}, {1,1,0,0}, {0,0,1,1}};
vector<vector<int>> ans = nearest(grid);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
import java.util.*;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
static int[][] nearest(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
// to store the answer
int[][] ans = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(ans[i], Integer.MAX_VALUE);
}
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
ans[i][j] = 0;
continue;
}
// iterate over all the cells
// and find the distance of the nearest 1
for (int k = 0; k < n; k++) {
for (int l = 0; l < m; l++) {
if (grid[k][l] == 1) {
ans[i][j] = Math.min(ans[i][j],
Math.abs(i - k) + Math.abs(j - l));
}
}
}
}
}
return ans;
}
public static void main(String[] args) {
int[][] grid = {{0,1,1,0}, {1,1,0,0}, {0,0,1,1}};
int[][] ans = nearest(grid);
for (int i = 0; i < ans.length; i++) {
for (int j = 0; j < ans[i].length; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
}
}
Python
# Function to find the distance of nearest cell
# having 1 for each cell of the matrix.
def nearest(grid):
n = len(grid)
m = len(grid[0])
# to store the answer
ans = [[float('inf')] * m for _ in range(n)]
# visit each cell of the grid
for i in range(n):
for j in range(m):
# if the cell has 1,
# then the distance is 0
if grid[i][j] == 1:
ans[i][j] = 0
continue
# iterate over all the cells
# and find the distance of the nearest 1
for k in range(n):
for l in range(m):
if grid[k][l] == 1:
ans[i][j] = min(ans[i][j],
abs(i - k) + abs(j - l))
return ans
if __name__ == "__main__":
grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]]
ans = nearest(grid)
for i in range(len(ans)):
for j in range(len(ans[i])):
print(ans[i][j], end=" ")
print()
C#
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
using System;
using System.Collections.Generic;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
static List<List<int>> nearest(List<List<int>> grid) {
int n = grid.Count;
int m = grid[0].Count;
// to store the answer
List<List<int>> ans = new List<List<int>>();
for (int i = 0; i < n; i++) {
List<int> temp = new List<int>();
for (int j = 0; j < m; j++) {
temp.Add(int.MaxValue);
}
ans.Add(temp);
}
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
ans[i][j] = 0;
continue;
}
// iterate over all the cells
// and find the distance of the nearest 1
for (int k = 0; k < n; k++) {
for (int l = 0; l < m; l++) {
if (grid[k][l] == 1) {
ans[i][j] = Math.Min(ans[i][j],
Math.Abs(i - k) + Math.Abs(j - l));
}
}
}
}
}
return ans;
}
static void Main() {
List<List<int>> grid = new List<List<int>> {
new List<int> {0, 1, 1, 0},
new List<int> {1, 1, 0, 0},
new List<int> {0, 0, 1, 1}
};
List<List<int>> ans = nearest(grid);
for (int i = 0; i < ans.Count; i++) {
for (int j = 0; j < ans[i].Count; j++) {
Console.Write(ans[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
function nearest(grid) {
let n = grid.length;
let m = grid[0].length;
// to store the answer
let ans = new Array(n);
for (let i = 0; i < n; i++) {
ans[i] = new Array(m).fill(Infinity);
}
// visit each cell of the grid
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] === 1) {
ans[i][j] = 0;
continue;
}
// iterate over all the cells
// and find the distance of the nearest 1
for (let k = 0; k < n; k++) {
for (let l = 0; l < m; l++) {
if (grid[k][l] === 1) {
ans[i][j] =
Math.min(ans[i][j], Math.abs(i - k) +
Math.abs(j - l));
}
}
}
}
}
return ans;
}
let grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]];
let ans = nearest(grid);
for (let i = 0; i < ans.length; i++) {
console.log(ans[i].join(" "));
}
Output1 0 0 1
0 0 1 1
1 1 0 0
[Expected Approach] - Using Breadth First Search - O(n * m) Time and O(n * m) Space
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 for every 1 in the queue.
Follow the given steps to solve the problem:
- Create a 2d array ans[][] of order n*m to store the results.
- 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 given the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
vector<vector<int>> nearest(vector<vector<int>> &grid) {
int n = grid.size();
int m = grid[0].size();
// to store the answer
vector<vector<int>> ans(n, vector<int>(m, INT_MAX));
// to store the indices of the cells having 1
queue<pair<int, int>> q;
// visit each cell of the grid
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
// if the cell has 1,
// then the distance is 0
if(grid[i][j] == 1) {
ans[i][j] = 0;
q.push({i, j});
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while(!q.empty()) {
int len = q.size();
for(int i = 0; i<len; i++) {
int x = q.front().first;
int y = q.front().second;
q.pop();
// check all the four directions
vector<vector<int>> directions =
{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int j = 0; j < directions.size(); j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x+dx >= 0 && x+dx < n && y+dy >= 0 &&
y+dy < m && ans[x+dx][y+dy] == INT_MAX) {
ans[x+dx][y+dy] = ans[x][y] + 1;
q.push({x+dx, y+dy});
}
}
}
}
return ans;
}
int main() {
vector<vector<int>> grid = {{0,1,1,0}, {1,1,0,0}, {0,0,1,1}};
vector<vector<int>> ans = nearest(grid);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix
import java.util.*;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix
static int[][] nearest(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
// to store the answer
int[][] ans = new int[n][m];
for (int i = 0; i < n; i++) {
Arrays.fill(ans[i], Integer.MAX_VALUE);
}
// to store the indices of the cells having 1
Queue<int[]> q = new LinkedList<>();
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
ans[i][j] = 0;
q.add(new int[]{i, j});
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (!q.isEmpty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
int[] cell = q.poll();
int x = cell[0];
int y = cell[1];
// check all the four directions
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int j = 0; j < directions.length; j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x + dx >= 0 && x + dx < n &&
y + dy >= 0 && y + dy < m &&
ans[x + dx][y + dy] == Integer.MAX_VALUE) {
ans[x + dx][y + dy] = ans[x][y] + 1;
q.add(new int[]{x + dx, y + dy});
}
}
}
}
return ans;
}
public static void main(String[] args) {
int[][] grid = {{0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 1, 1}};
int[][] ans = nearest(grid);
for (int i = 0; i < ans.length; i++) {
for (int j = 0; j < ans[i].length; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
}
}
Python
# Function to find the distance of nearest cell
# having 1 for each cell of the matrix.
def nearest(grid):
n = len(grid)
m = len(grid[0])
# to store the answer
ans = [[float('inf')] * m for _ in range(n)]
# to store the indices of the cells having 1
from collections import deque
q = deque()
# visit each cell of the grid
for i in range(n):
for j in range(m):
# if the cell has 1,
# then the distance is 0
if grid[i][j] == 1:
ans[i][j] = 0
q.append((i, j))
# iterate over all the cells
# and find the distance of the nearest 1
while q:
len_q = len(q)
for _ in range(len_q):
x, y = q.popleft()
# check all the four directions
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for j in range(len(directions)):
dx = directions[j][0]
dy = directions[j][1]
# if the cell is within the grid
# and the distance is not calculated yet
if x + dx >= 0 and x + dx < n and \
y + dy >= 0 and y + dy < m and \
ans[x + dx][y + dy] == float('inf'):
ans[x + dx][y + dy] = ans[x][y] + 1
q.append((x + dx, y + dy))
return ans
if __name__ == "__main__":
grid = [[0, 1, 1, 0], [1, 1, 0, 0], [0, 0, 1, 1]]
ans = nearest(grid)
for i in range(len(ans)):
for j in range(len(ans[i])):
print(ans[i][j], end=" ")
print()
C#
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
using System;
using System.Collections.Generic;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
static List<List<int>> nearest(List<List<int>> grid) {
int n = grid.Count;
int m = grid[0].Count;
// to store the answer
List<List<int>> ans = new List<List<int>>();
for (int i = 0; i < n; i++) {
List<int> row = new List<int>();
for (int j = 0; j < m; j++) {
row.Add(int.MaxValue);
}
ans.Add(row);
}
// to store the indices of the cells having 1
Queue<(int, int)> q = new Queue<(int, int)>();
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
ans[i][j] = 0;
q.Enqueue((i, j));
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (q.Count > 0) {
int len = q.Count;
for (int i = 0; i < len; i++) {
var cell = q.Dequeue();
int x = cell.Item1;
int y = cell.Item2;
// check all the four directions
List<List<int>> directions = new List<List<int>> {
new List<int> {0, 1},
new List<int> {0, -1},
new List<int> {1, 0},
new List<int> {-1, 0}
};
for (int j = 0; j < directions.Count; j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x + dx >= 0 && x + dx < n &&
y + dy >= 0 && y + dy < m &&
ans[x + dx][y + dy] == int.MaxValue) {
ans[x + dx][y + dy] = ans[x][y] + 1;
q.Enqueue((x + dx, y + dy));
}
}
}
}
return ans;
}
static void Main() {
List<List<int>> grid = new List<List<int>> {
new List<int> {0, 1, 1, 0},
new List<int> {1, 1, 0, 0},
new List<int> {0, 0, 1, 1}
};
List<List<int>> ans = nearest(grid);
for (int i = 0; i < ans.Count; i++) {
for (int j = 0; j < ans[i].Count; j++) {
Console.Write(ans[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
function nearest(grid) {
let n = grid.length;
let m = grid[0].length;
// to store the answer
let ans = new Array(n);
for (let i = 0; i < n; i++) {
ans[i] = new Array(m).fill(Number.MAX_SAFE_INTEGER);
}
// to store the indices of the cells having 1
let q = [];
// visit each cell of the grid
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] === 1) {
ans[i][j] = 0;
q.push([i, j]);
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (q.length > 0) {
let len = q.length;
for (let i = 0; i < len; i++) {
let cell = q.shift();
let x = cell[0], y = cell[1];
// check all the four directions
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
for (let j = 0; j < directions.length; j++) {
let dx = directions[j][0];
let dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x + dx >= 0 && x + dx < n &&
y + dy >= 0 && y + dy < m &&
ans[x + dx][y + dy] === Number.MAX_SAFE_INTEGER) {
ans[x + dx][y + dy] = ans[x][y] + 1;
q.push([x + dx, y + dy]);
}
}
}
}
return ans;
}
let grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]];
let ans = nearest(grid);
for (let i = 0; i < ans.length; i++) {
console.log(ans[i].join(" "));
}
Output1 0 0 1
0 0 1 1
1 1 0 0
[Optimized Approach] - Using Space Optimized BFS - O(n * m) Time and O(1) Space
In the above approach, we are creating a 2d array ans[][] of order n * m to store the results, but instead of doing so, we can modify the input array itself. The cells having value 1, will be marked 0, and the remaining cells will be marked INT_MAX, and we will operate similar to above approach.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
vector<vector<int>> nearest(vector<vector<int>> &grid) {
int n = grid.size();
int m = grid[0].size();
// to store the indices of the cells having 1
queue<pair<int, int>> q;
// visit each cell of the grid
for(int i = 0; i<n; i++) {
for(int j = 0; j<m; j++) {
// if the cell has 1,
// then the distance is 0
if(grid[i][j] == 1) {
grid[i][j] = 0;
q.push({i, j});
}
else {
grid[i][j] = INT_MAX;
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while(!q.empty()) {
int len = q.size();
for(int i = 0; i<len; i++) {
int x = q.front().first;
int y = q.front().second;
q.pop();
// check all the four directions
vector<vector<int>> directions =
{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int j = 0; j < directions.size(); j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x+dx >= 0 && x+dx < n && y+dy >= 0 &&
y+dy < m && grid[x+dx][y+dy] == INT_MAX) {
grid[x+dx][y+dy] = grid[x][y] + 1;
q.push({x+dx, y+dy});
}
}
}
}
return grid;
}
int main() {
vector<vector<int>> grid = {{0,1,1,0}, {1,1,0,0}, {0,0,1,1}};
vector<vector<int>> ans = nearest(grid);
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix
import java.util.*;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix
static int[][] nearest(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
// to store the indices of the cells having 1
Queue<int[]> q = new LinkedList<>();
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
grid[i][j] = 0;
q.add(new int[]{i, j});
}
else {
grid[i][j] = Integer.MAX_VALUE;
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (!q.isEmpty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
int[] cell = q.poll();
int x = cell[0];
int y = cell[1];
// check all the four directions
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for (int j = 0; j < directions.length; j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x + dx >= 0 && x + dx < n &&
y + dy >= 0 && y + dy < m &&
grid[x + dx][y + dy] == Integer.MAX_VALUE) {
grid[x + dx][y + dy] = grid[x][y] + 1;
q.add(new int[]{x + dx, y + dy});
}
}
}
}
return grid;
}
public static void main(String[] args) {
int[][] grid = {{0,1,1,0}, {1,1,0,0}, {0,0,1,1}};
int[][] ans = nearest(grid);
for (int i = 0; i < ans.length; i++) {
for (int j = 0; j < ans[i].length; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
}
}
Python
# Function to find the distance of nearest cell
# having 1 for each cell of the matrix.
def nearest(grid):
n = len(grid)
m = len(grid[0])
# to store the indices of the cells having 1
from collections import deque
q = deque()
# visit each cell of the grid
for i in range(n):
for j in range(m):
# if the cell has 1,
# then the distance is 0
if grid[i][j] == 1:
grid[i][j] = 0
q.append((i, j))
else:
grid[i][j] = float('inf')
# iterate over all the cells
# and find the distance of the nearest 1
while q:
len_q = len(q)
for _ in range(len_q):
x, y = q.popleft()
# check all the four directions
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for j in range(len(directions)):
dx = directions[j][0]
dy = directions[j][1]
# if the cell is within the grid
# and the distance is not calculated yet
if x+dx >= 0 and x+dx < n and \
y+dy >= 0 and y+dy < m and \
grid[x+dx][y+dy] == float('inf'):
grid[x+dx][y+dy] = grid[x][y] + 1
q.append((x+dx, y+dy))
return grid
if __name__ == "__main__":
grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]]
ans = nearest(grid)
for i in range(len(ans)):
for j in range(len(ans[i])):
print(ans[i][j], end=" ")
print()
C#
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
using System;
using System.Collections.Generic;
class GfG {
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
static List<List<int>> nearest(List<List<int>> grid) {
int n = grid.Count;
int m = grid[0].Count;
// to store the indices of the cells having 1
Queue<(int, int)> q = new Queue<(int, int)>();
// visit each cell of the grid
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] == 1) {
grid[i][j] = 0;
q.Enqueue((i, j));
}
else {
grid[i][j] = int.MaxValue;
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (q.Count > 0) {
int len = q.Count;
for (int i = 0; i < len; i++) {
var cell = q.Dequeue();
int x = cell.Item1;
int y = cell.Item2;
// check all the four directions
List<List<int>> directions = new List<List<int>> {
new List<int> {0, 1},
new List<int> {0, -1},
new List<int> {1, 0},
new List<int> {-1, 0}
};
for (int j = 0; j < directions.Count; j++) {
int dx = directions[j][0];
int dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x+dx >= 0 && x+dx < n &&
y+dy >= 0 && y+dy < m &&
grid[x+dx][y+dy] == int.MaxValue) {
grid[x+dx][y+dy] = grid[x][y] + 1;
q.Enqueue((x+dx, y+dy));
}
}
}
}
return grid;
}
static void Main() {
List<List<int>> grid = new List<List<int>> {
new List<int> {0,1,1,0},
new List<int> {1,1,0,0},
new List<int> {0,0,1,1}
};
List<List<int>> ans = nearest(grid);
for (int i = 0; i < ans.Count; i++) {
for (int j = 0; j < ans[i].Count; j++) {
Console.Write(ans[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// Function to find the distance of nearest cell
// having 1 for each cell of the matrix.
function nearest(grid) {
let n = grid.length;
let m = grid[0].length;
// to store the indices of the cells having 1
let q = [];
// visit each cell of the grid
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// if the cell has 1,
// then the distance is 0
if (grid[i][j] === 1) {
grid[i][j] = 0;
q.push([i, j]);
}
else {
grid[i][j] = Number.MAX_SAFE_INTEGER;
}
}
}
// iterate over all the cells
// and find the distance of the nearest 1
while (q.length > 0) {
let len = q.length;
for (let i = 0; i < len; i++) {
let cell = q.shift();
let x = cell[0];
let y = cell[1];
// check all the four directions
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];
for (let j = 0; j < directions.length; j++) {
let dx = directions[j][0];
let dy = directions[j][1];
// if the cell is within the grid
// and the distance is not calculated yet
if (x+dx >= 0 && x+dx < n &&
y+dy >= 0 && y+dy < m &&
grid[x+dx][y+dy] === Number.MAX_SAFE_INTEGER) {
grid[x+dx][y+dy] = grid[x][y] + 1;
q.push([x+dx, y+dy]);
}
}
}
}
return grid;
}
let grid = [[0,1,1,0], [1,1,0,0], [0,0,1,1]];
let ans = nearest(grid);
for (let i = 0; i < ans.length; i++) {
console.log(ans[i].join(" "));
}
Output1 0 0 1
0 0 1 1
1 1 0 0
Similar Reads
Exit Point in a Binary Matrix Given a binary matrix of size N x M, you enter the matrix at cell (0, 0) in the left to the right direction. Whenever encountering a 0 retain in the same direction if encountered a 1 change direction to the right of the current direction and change that 1 value to 0, find out exit point from the Mat
8 min read
Unique cells in a binary matrix Given a matrix of size n à m consisting of 0's and 1's. We need to find the number of unique cells with value 1 such that the corresponding entire row and the entire column do not have another 1. Return the number of unique cells. Examples: Input : mat[][] = {0, 1, 0, 0 0, 0, 1, 0 1, 0, 0, 1} Answer
11 min read
Distance of nearest cell having 1 in a binary matrix Given a binary grid of n*m. Find the distance of the nearest 1 in the grid 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. Th
15+ min read
Shortest path in a Binary Maze Given an M x N matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and
15+ min read
Maximum Number of Ones in Binary Matrix Given a binary matrix mat[][] with dimensions m * n, and any square sub-matrix of mat of size len * len has at most k ones. The task is to return the maximum possible number of ones that the matrix mat can have. Example: Input: m = 3, n = 3, len = 2, k = 1Output: 4Explanation: In a 3*3 matrix, no 2*
8 min read
Find duplicate rows in a binary matrix Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicates of rows that are already present in the matrix. Examples: Input : {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {1, 0, 1, 1, 0, 0}, {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {0, 0, 1, 0, 0, 1}.Output :There
15+ min read
Print unique rows in a given Binary matrix Given a binary matrix, print all unique rows of the given matrix. Example: Input: {0, 1, 0, 0, 1} {1, 0, 1, 1, 0} {0, 1, 0, 0, 1} {1, 1, 1, 0, 0} Output: 0 1 0 0 1 1 0 1 1 0 1 1 1 0 0 Explanation: The rows are r1={0, 1, 0, 0, 1}, r2={1, 0, 1, 1, 0}, r3={0, 1, 0, 0, 1}, r4={1, 1, 1, 0, 0}, As r1 = r3
15+ min read
Search element in a sorted matrix Given a sorted matrix mat[][] of size nxm and an element x, the task is to find if x is present in the matrix or not. Matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row i, where 1 <= i <= n-1, the first element of row i is greater than or equal
13 min read
Total coverage of all zeros in a binary matrix Given a binary matrix that is, it contains 0s and 1s only, we need to find sum of coverage of all zeros of the matrix where coverage for a particular 0 is defined as total number of ones around a zero in left, right, up and bottom directions. The ones can be anywhere till corner point in a direction
10 min read