描述
給定一個N x M的01矩陣,其中1表示陸地,0表示水域。對於每一個位置,求出它距離最近的水域的距離是多少。
矩陣中每個位置與它上下左右相鄰的格子距離爲1。
輸入
第一行包含兩個整數,N和M。
以下N行每行M個0或者1,代表地圖。
數據保證至少有1塊水域。
對於30%的數據,1 <= N, M <= 100
對於100%的數據,1 <= N, M <= 800
輸出
輸出N行,每行M個空格分隔的整數。每個整數表示該位置距離最近的水域的距離。
樣例輸入
4 4
0110
1111
1111
0110
樣例輸出
0 1 1 0
1 2 2 1
1 2 2 1
0 1 1 0
思路:
簡單的bfs,將0的點的集合放入隊列中進行bfs遍歷。每個點第一被訪問時,就是當前點到周圍水域的最近的距離
#include <bits/stdc++.h>
using namespace std;
const int maxn = 805;
int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
string g[maxn];
int res[maxn][maxn];
bool vis[maxn][maxn];
int n, m;
bool judge(int x, int y) {
if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && g[x][y] =='1')
return true;
return false;
}
void bfs(queue<pair<int,int>>q) {
while(!q.empty()) {
auto tmp = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int dx = tmp.first + dir[i][0];
int dy = tmp.second + dir[i][1];
if (judge(dx, dy)) {
vis[dx][dy] = 1;
res[dx][dy] = res[tmp.first][tmp.second] + 1;
q.push(make_pair(dx, dy));
}
}
}
}
void solve() {
cin >> n >> m;
queue<pair<int,int>>q;
for (int i = 0; i < n; ++i) {
cin >> g[i];
for (int j = 0; j < m; ++j) {
if (g[i][j] == '0') {
res[i][j] = 0;
q.push(make_pair(i,j));
}
}
}
bfs(q);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
cout << res[i][j]<< " ";
cout << endl;
}
}
int main() {
solve();
return 0;
}