https://www.acwing.com/problem/content/description/175/
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
string a[N];
int dist[N][N],n,m;
int dx[4]={-1,0,0,1};
int dy[4]={0,-1,1,0};
void bfs()
{
memset(dist,-1,sizeof dist);
queue<pair<int,int>>q;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='1') q.push({i,j}),dist[i][j]=0;
while(q.size())
{
auto u=q.front(); q.pop();
int x=u.first,y=u.second;
for(int i=0;i<4;i++)
{
int tempx=x+dx[i];
int tempy=y+dy[i];
if(tempx<0||tempx>=n||tempy<0||tempy>=m) continue;
if(dist[tempx][tempy]!=-1) continue;
dist[tempx][tempy]=dist[x][y]+1;
q.push({tempx,tempy});
}
}
}
int main(void)
{
cin>>n>>m;
for(int i=0;i<n;i++) cin>>a[i];
bfs();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++) cout<<dist[i][j]<<" ";
cout<<endl;
}
return 0;
}