SP206 BITMAP - Bitmap 灰 题解
思路
就是搜。
将所有为 1 的点加入队列,然后更新搜到的点离最近的 1 的距离。
代码
#include <bits/stdc++.h>
using namespace std;
const int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int t,n,m,a,ans[1010][1010];
struct node {int x,y,d;};
queue<node> q;
int main () {
cin>> t;
while (t--) {
cin>> n>> m;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++) {
scanf ("%1d",&a);
if (a==1) {
q.push ({i,j,0});
ans[i][j]=0;//为 1 的点的初始答案直接设为 0
} else ans[i][j]=INT_MAX;//为 0 的点的初始答案设为极大值
}
while (q.size ()) {
node now=q.front ();
q.pop ();
for (int i=0;i<4;i++) {
int dx=now.x+d[i][0];
int dy=now.y+d[i][1];
int dd=now.d+1;
if (dx>0&&dx<=n&&dy>0&&dy<=m&&dd<ans[dx][dy]) {
ans[dx][dy]=dd;
q.push ({dx,dy,dd});
}
}
}
for (int i=1;i<=n;i++) {
for (int j=1;j<=m;j++)
cout<< ans[i][j]<< " ";
puts ("");
}
}
return 0;
}

浙公网安备 33010602011771号