
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Nearest 1 in a Binary Matrix in C++
In this article, we will show you how to find the minimum distance from each cell in a binary matrix to the nearest cell that contains the digit 1. We will see brute force as well as optimized approaches.
Problem Statement
Given a binary matrix, our task is to calculate the minimum distance for each cell to the nearest cell that contains the value 1, and if the current cell itself has 1 as a value, the distance will be 0.
If the input matrix is as follows -
0 0 1 1 1 0 0 0 0
The output will be -
1 1 0 0 0 1 1 2
Brute Force Approach to find the Nearest 1
In this approach, we will know how we can find the nearest 1 cell for each cell in the simplest way. We will just use loops and conditions. Here, we traverse the whole matrix, and for each cell, we check all adjacent cells (up, down, left, right) to find the nearest cell that contains the value 1.
Steps
- Initialize the matrix of desired size.
- Initialize another matrix of the same size to store distances.
- Iterate over the entire matrix. If the current cell value is 1, set the distance to 0 (the distance from 1to 1 is 0).
- If the current cell value is 0. Iterate over the entire matrix again.
- If the cell is 1, calculate the distance from the current cell.
- Update the minimum distance.
Below is the brute force program for finding the Nearest 1 to each cell -
#include <bits/stdc++.h> using namespace std; vector<vector<int>> findNearest1Distance(vector<vector<int>>& matrix) { int rows = matrix.size(); if (rows == 0) { return matrix; } int cols = matrix[0].size(); vector<vector<int>> distance(rows, vector(cols, INT_MAX)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == 1) { distance[i][j] = 0; }else if (matrix[i][j] == 0) { for (int k = 0; k < rows; k++) { for (int l = 0; l < cols; l++) { if (matrix[k][l] == 1) { distance[i][j] = min(distance[i][j], abs(k - i) + abs(l - j)); } } } } } } return distance; } int main() { vector<vector<int>> matrix{ {0, 0, 1}, {1, 1, 0}, {0, 0, 0} }; vector<vector<int>> result = findNearest1Distance(matrix); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << result[i][j] << " "; } cout << endl; } return 0; }
In the brute force approach, we check each cell in the matrix. For every 0, we look for the nearest 1 by calculating the distance to all other cells that contain 1. We then store the smallest distance found. For example, in the matrix:
0 0 1 1 0 0
Starting with the first cell (0,0), the closest 1 is at (0,2), so the distance is 2. We repeat this for each cell. This approach works, but is slow because it checks every possible distance. The final matrix of distances looks like this:
2 1 0 3 2 1
Optimized approach using BFS
This approach uses a queue to perform a breadth-first search (BFS) from all cells that contain a 1. This helps us to efficiently propagate distances to adjacent cells. The time complexity of this approach is O(N * M).
Steps
- Initialize the matrix of desired size.
- Initialize another matrix of the same size to store distances, with all values set to INT_MAX.
- Create a queue to help with BFS traversal.
- Iterate over the entire matrix. If the current cell value is 1, set the distance to 0 and push the cell into the queue.
- Define directions for traversal (up, down, left, right).
- While the queue is not empty, pop a cell from the queue.
- For each direction, calculate the new position (neighboring cell).
- If the new position is valid (inside the matrix) and gives a smaller distance, update the distance and push the new cell into the queue.
Below is the program for finding the nearest 1 in each cell for every cell using BFS -
#include <bits/stdc++.h> using namespace std; vector<vector<int>> findNearest1Distance(vector<vector<int>>& matrix) { int rows = matrix.size(); if (rows == 0) { return matrix; } int cols = matrix[0].size(); vector<vector<int>> distance(rows, vector<int>(cols, INT_MAX)); queue<pair<int, int>> q; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == 1) { distance[i][j] = 0; q.push({i, j}); } } } vector<vector<int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (auto& dir : directions) { int nx = x + dir[0]; int ny = y + dir[1]; if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) { if (distance[nx][ny] > distance[x][y] + 1) { distance[nx][ny] = distance[x][y] + 1; q.push({nx, ny}); } } } } return distance; } int main() { vector<vector<int>> matrix{ {0, 0, 1}, {1, 1, 0}, {0, 0, 0} }; vector<vector<int>> result = findNearest1Distance(matrix); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << result[i][j] << " "; } cout << endl; } return 0; }
In the optimized approach, we are using BFS to efficiently find the nearest 1 for each cell. We start by adding all the cells that contain 1 to a queue and set their distances to 0. Then, we process each cell level by level, updating the distances for its adjacent cells (up, down, left, right). For example, in the matrix:
0 0 1 1 0 0
We add all the 1 cells to the queue. The cell (0,2) has a distance of 0, and its neighbors will be updated next. The BFS continues, updating distances for cells farther away. The final matrix looks like this:
2 1 0 0 1 2
This method is much faster than brute force because it processes each cell only once.