题目:
见https://www.acwing.com/problem/content/169/
思路:
见《算法进阶竞赛指南》P116
代码:
//简单的bfs逐层递增
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N=1010;
int d[N][N],n,m;//d是存答案的二维数组
typedef pair<int,int> PII;
queue<PII> q;
int dx[4]={0,0,1,-1},dy[4]={-1,1,0,0};
void bfs()
{
while(!q.empty())
{
auto t=q.front();
q.pop();
int x=t.first,y=t.second;
for(int i=0;i<4;i++)
{
int nx=x+dx[i],ny=y+dy[i];
if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&d[nx][ny]==-1)//该点坐标未超过边界并且是第一次访问
{
q.push({nx,ny});
d[nx][ny]=d[x][y]+1;
}
}
}
}
int main()
{
cin>>n>>m;
memset(d,-1,sizeof d);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
char c;
cin>>c;
if(c=='1')
{
d[i][j]=0;
q.push({i,j});
}
}
bfs();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
cout<<d[i][j]<<" ";
cout<<endl;
}
return 0;
}