Skip to content

Commit eeadb7e

Browse files
authored
Update BFS_on_grid.cpp
1 parent 84cd614 commit eeadb7e

File tree

1 file changed

+42
-32
lines changed

1 file changed

+42
-32
lines changed

BFS_on_grid.cpp

+42-32
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/*
22
implementation of BFS on 2D grid
33
@author Amirul islam :: Nov 1, 2019
4+
@modified Amirul islam :: Jan 24, 2021
45
_
56
_|_ o._ o._ __|_| _. _|_
67
_>| ||| ||| |(_|| |(_|_>| |
@@ -9,70 +10,79 @@
910

1011
#include <bits/stdc++.h>
1112
using namespace std;
12-
#define pii pair <int, int>
13-
#define mp make_pair
14-
#define isInside(x, y, row, col) (x >= 0 && x < row && y >= 0 && y < col)
1513

1614
const int mx = 1e3;
1715

18-
int dx[] = {-1, 0, 1, 0};
19-
int dy[] = {0, 1, 0, -1};
20-
21-
char cell[mx][mx];
22-
bool vis[mx][mx];
16+
char grid[mx][mx];
17+
int vis [mx][mx];
2318
int dis[mx][mx];
2419

20+
int dx[] = {0, 1, 0, -1};
21+
int dy[] = {1, 0, -1, 0};
22+
23+
bool isInside(int x, int y, int row, int col) {
24+
return x >= 0 && x < row && y >= 0 && y < col;
25+
}
26+
2527
void bfs(int sx, int sy, int row, int col) {
26-
vis[sx][sy] = 1;
27-
queue <pii> q;
28-
q.push(mp(sx, sy));
28+
vis[sx][sy] = true;
29+
queue < pair <int, int> > q;
30+
q.push(make_pair(sx, sy));
31+
2932
while (!q.empty()) {
30-
pii top = q.front();
33+
pair <int, int> top = q.front();
3134
q.pop();
35+
3236
for (int k = 0; k < 4; k++) {
3337
int nx = top.first + dx[k];
3438
int ny = top.second + dy[k];
35-
if (isInside(nx, ny, row, col) && cell[nx][ny] != '#' && !vis[nx][ny]) {
36-
vis[nx][ny] = 1;
37-
dis[nx][ny] = dis[top.first][top.second] + 1;
38-
q.push(mp(nx, ny));
39-
}
39+
40+
if (isInside(nx, ny, row, col) &&
41+
grid[nx][ny] != '#' && !vis[nx][ny]) {
42+
vis[nx][ny] = true;
43+
dis[nx][ny] = dis[top.first][top.second] + 1;
44+
q.push(make_pair(nx, ny));
45+
}
46+
}
47+
}
48+
}
49+
50+
void printGrid(int row, int col) {
51+
for (int i = 0; i < row; i++) {
52+
for (int j = 0; j < col; j++) {
53+
cout << dis[i][j] << " ";
4054
}
55+
cout << "\n";
4156
}
4257
}
4358

4459
int main() {
45-
//freopen("in", "r", stdin);
46-
//ios_base::sync_with_stdio(0);
47-
//cin.tie(NULL);
60+
freopen("in", "r", stdin);
61+
62+
int row, col;
63+
cin >> row >> col;
4864

49-
int row, col, sx, sy, cnt(0);
50-
scanf("%d %d", &row, &col);
5165
swap(row, col);
66+
5267
for (int i = 0; i < row; i++) {
53-
scanf("%s", cell[i]);
68+
cin >> grid[i];
5469
}
70+
5571
bfs(0, 0, row, col);
56-
for (int i = 0; i < row; i++) {
57-
for (int j = 0; j < col; j++) printf("%d ", dis[i][j]);
58-
printf("\n");
59-
}
72+
73+
printGrid(row, col);
74+
6075
return 0;
6176
}
6277

6378
/*
64-
6579
Input:
66-
6780
3 3
6881
...
6982
#.#
7083
...
71-
7284
Output:
73-
7485
0 1 2
7586
0 2 0
7687
4 3 4
77-
7888
*/

0 commit comments

Comments
 (0)