思路:曼哈顿距离那就上下左右四个方向走每次加1,bfs去搜,以所有的1为起点入队开始。
#pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<iomanip>
#include<cstring>
#include<time.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e5+10;
const int inf=0x3f3f3f3f;
const int maxx=2e5+7;
const double eps=1e-6;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1)
res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
int n, m,k;
int dir[4][2]={
{
-1,0},{
0,1},{
1,0},{
0,-1}};
char mp[1005][1005];
int vis[1005][1005];
int sx,sy,ex,ey;
queue<PII> q;
void bfs()
{
int ans=0;
memset(vis,-1,sizeof vis);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(mp[i][j]=='1'){
vis[i][j]=0;
q.push({
i,j});
}
}
}
while(!q.empty())
{
PII now=q.front();q.pop();
for(int i=0;i<4;i++)
{
int xx=now.first+dir[i][0];
int yy=now.second+dir[i][1];
if(xx<1||xx>n||yy<1||yy>m)continue;
if(vis[xx][yy]!=-1)continue;
vis[xx][yy]=vis[now.first][now.second]+1;
q.push({
xx,yy});
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%d ",vis[i][j]);
puts("");
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s",mp[i]+1);
}
bfs();
return 0;
}