Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Distance of nearest 0 in binary matrix in JavaScript
A binary matrix is an array of arrays containing only 0 or 1. We are required to write a JavaScript function that takes in a binary matrix as the only argument.
Our function should create a new matrix containing the same number of rows and columns, and for each element of the original matrix the resulting matrix should contain that element's nearest distance from 0 in the original matrix.
We have to keep in mind that while calculating distance it can move either horizontally or vertically and not diagonally. And it's guaranteed that the matrix contains at least one 0.
Problem Example
If the input matrix is:
const arr = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 1]
];
Then the output matrix should be:
const output = [
[0, 0, 0],
[0, 1, 0],
[1, 2, 1]
];
Algorithm Overview
The solution uses a Breadth-First Search (BFS) approach:
- Initialize all 0s with distance 0
- Initialize all 1s with maximum distance
- Use BFS to propagate minimum distances from all 0s simultaneously
Implementation
const arr = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 1],
];
const findNearestDistance = (arr = []) => {
let queue = [];
let res = arr.map((el, ind) => el.map((subEl, subInd) => {
if (subEl === 0) {
queue.push([ind, subInd]);
return 0;
}
return Number.MAX_SAFE_INTEGER;
}));
const updateAdjacent = (ind, subInd, min, nextQueue = []) => {
if (ind = arr.length || subInd >= arr[0].length) {
return;
}
if (res[ind][subInd]
Output
[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 1, 2, 1 ] ]
How It Works
The algorithm works in phases:
-
Initialization: All zeros get distance 0, all ones get infinity
-
BFS Expansion: Each iteration processes cells at current distance and updates their neighbors
-
Distance Update: Only update if we found a shorter path
Time Complexity
Time complexity is O(m × n) where m and n are matrix dimensions, as each cell is visited once. Space complexity is also O(m × n) for the result matrix and queue.
Conclusion
This BFS approach efficiently finds the minimum distance from each cell to the nearest zero in a binary matrix. The algorithm ensures optimal distances by processing cells level by level.
