Skip to content

Commit c677f09

Browse files
committed
Add: Nearest 1 Distance in Grid (BFS) in C++
- Implements BFS traversal to compute distance of nearest 1 for each cell in a binary grid - Uses multi-source BFS starting from all cells containing 1 - Time Complexity: O(N*M), where N = rows, M = columns - Space Complexity: O(N*M) for distance and visited matrices + queue storage
1 parent e7830ff commit c677f09

File tree

1 file changed

+110
-53
lines changed

1 file changed

+110
-53
lines changed
Lines changed: 110 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,114 @@
1-
#include<bits/stdc++.h>
1+
#include <bits/stdc++.h>
22
using namespace std;
33

4+
/*
5+
Algorithm: BFS-based Distance of Nearest 1 in a Binary Grid
6+
7+
Given a binary matrix 'grid', we want to calculate, for each cell,
8+
the distance to the nearest cell containing 1.
9+
10+
Steps:
11+
1. Initialize a 'distance' matrix of same size as grid to store results.
12+
2. Initialize a 'visited' matrix to track which cells have been processed.
13+
3. Use a queue to perform multi-source BFS:
14+
- Push all cells containing 1 into the queue with distance 0.
15+
4. Perform BFS:
16+
- For each cell, explore its 4 neighbors (up, down, left, right).
17+
- If a neighbor is valid and unvisited, mark it visited and push it into the queue with incremented distance.
18+
5. Continue until all reachable cells are processed.
19+
6. Return the 'distance' matrix.
20+
21+
Time Complexity: O(N*M), where N = number of rows, M = number of columns
22+
- Each cell is processed at most once.
23+
24+
Space Complexity: O(N*M)
25+
- For 'visited' and 'distance' matrices + queue storage
26+
*/
27+
428
class Solution
529
{
6-
public:
7-
//Function to find the distance of nearest 1 in the grid for each cell.
8-
vector<vector<int>>nearest(vector<vector<int>>grid)
9-
{
10-
int n = grid.size();
11-
int m = grid[0].size();
12-
// visited and distance matrix
13-
vector<vector<int>> vis(n, vector<int>(m, 0));
14-
vector<vector<int>> dist(n, vector<int>(m, 0));
15-
// <coordinates, steps>
16-
queue<pair<pair<int,int>, int>> q;
17-
// traverse the matrix
18-
for(int i = 0;i<n;i++) {
19-
for(int j = 0;j<m;j++) {
20-
// start BFS if cell contains 1
21-
if(grid[i][j] == 1) {
22-
q.push({{i,j}, 0});
23-
vis[i][j] = 1;
24-
}
25-
else {
26-
// mark unvisited
27-
vis[i][j] = 0;
28-
}
29-
}
30-
}
31-
32-
int delrow[] = {-1, 0, +1, 0};
33-
int delcol[] = {0, +1, 0, -1};
34-
35-
// traverse till queue becomes empty
36-
while(!q.empty()) {
37-
int row = q.front().first.first;
38-
int col = q.front().first.second;
39-
int steps = q.front().second;
40-
q.pop();
41-
dist[row][col] = steps;
42-
// for all 4 neighbours
43-
for(int i = 0;i<4;i++) {
44-
int nrow = row + delrow[i];
45-
int ncol = col + delcol[i];
46-
// check for valid unvisited cell
47-
if(nrow >= 0 && nrow < n && ncol >= 0 && ncol < m
48-
&& vis[nrow][ncol] == 0) {
49-
vis[nrow][ncol] = 1;
50-
q.push({{nrow, ncol}, steps+1});
51-
}
52-
}
53-
}
54-
// return distance matrix
55-
return dist;
56-
}
57-
};
30+
public:
31+
vector<vector<int>> nearest(vector<vector<int>>& grid)
32+
{
33+
int rows = grid.size();
34+
int cols = grid[0].size();
35+
36+
// Distance matrix to store minimum distance to nearest 1
37+
vector<vector<int>> distance(rows, vector<int>(cols, 0));
38+
39+
// Visited matrix to track processed cells
40+
vector<vector<int>> visited(rows, vector<int>(cols, 0));
41+
42+
// Queue to perform BFS, stores {{row, col}, distance_from_1}
43+
queue<pair<pair<int,int>, int>> bfsQueue;
44+
45+
// Step 1: Initialize BFS with all cells containing 1
46+
for(int r = 0; r < rows; r++)
47+
{
48+
for(int c = 0; c < cols; c++)
49+
{
50+
if(grid[r][c] == 1)
51+
{
52+
bfsQueue.push({{r, c}, 0}); // Push coordinates with distance 0
53+
visited[r][c] = 1; // Mark as visited
54+
}
55+
}
56+
}
57+
58+
// Direction vectors for 4 neighbors: up, right, down, left
59+
int dRow[] = {-1, 0, 1, 0};
60+
int dCol[] = {0, 1, 0, -1};
61+
62+
// Step 2: BFS traversal
63+
while(!bfsQueue.empty())
64+
{
65+
int currentRow = bfsQueue.front().first.first;
66+
int currentCol = bfsQueue.front().first.second;
67+
int currentDistance = bfsQueue.front().second;
68+
bfsQueue.pop();
69+
70+
distance[currentRow][currentCol] = currentDistance;
71+
72+
// Explore 4 neighbors
73+
for(int i = 0; i < 4; i++)
74+
{
75+
int neighborRow = currentRow + dRow[i];
76+
int neighborCol = currentCol + dCol[i];
77+
78+
// Check if neighbor is inside grid and unvisited
79+
if(neighborRow >= 0 && neighborRow < rows && neighborCol >= 0 && neighborCol < cols
80+
&& visited[neighborRow][neighborCol] == 0)
81+
{
82+
visited[neighborRow][neighborCol] = 1;
83+
bfsQueue.push({{neighborRow, neighborCol}, currentDistance + 1});
84+
}
85+
}
86+
}
87+
88+
return distance; // Return final distance matrix
89+
}
90+
};
91+
92+
// Driver code to test the Solution class
93+
int main()
94+
{
95+
Solution sol;
96+
97+
vector<vector<int>> grid = {
98+
{0, 0, 1},
99+
{0, 1, 0},
100+
{0, 0, 0}
101+
};
102+
103+
vector<vector<int>> result = sol.nearest(grid);
104+
105+
cout << "Distance matrix:\n";
106+
for(auto &row : result)
107+
{
108+
for(auto &val : row)
109+
cout << val << " ";
110+
cout << "\n";
111+
}
112+
113+
return 0;
114+
}

0 commit comments

Comments
 (0)