给定一个N x M的01矩阵,其中1表示陆地,0表示水域。对于每一个位置,求出它距离最近的水域
的距离是多少。
矩阵中每个位置与它上下左右相邻的格子距离为1。
Input第一行包含两个整数,N和M。
以下N行每行M个0或者1,代表地图。
数据保证至少有1块水域。
对于30%的数据,1 <= N, M <= 100
对于100%的数据,1 <= N, M <= 800
Output输出N行,每行M个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。
4 4 0110 1111 1111 0110Sample Output
0 1 1 0
1 2 2 1
1 2 2 1
0 1 1 0
思路:广搜得解。只不过要从每个水域0开始广搜。如果每个点都搜一遍会超时。
做题心得:样例一直过不去,一直全0输出。后来发现,我在int main()中多定义了变量n,m;
代码:
#include<queue>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m;
int book[810][810]={0},b[810][810]={0};
char tu[810][810];
struct mm
{
int x,y,step;
};
mm now,nex;
queue<mm>q;
int ne[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void bfs()
{
while(!q.empty())
{
now=q.front();
nex.step=now.step+1;
for(int k=0;k<4;k++)
{
nex.x=now.x+ne[k][0];
nex.y=now.y+ne[k][1];
if(nex.x<0||nex.x>=n||nex.y<0||nex.y>=m||book[nex.x][nex.y]==1)
continue;
q.push(nex);
book[nex.x][nex.y]=1;
b[nex.x][nex.y]=nex.step;
}
q.pop();
}
}
int main()
{
// int n,m; 多定义的n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%s",tu[i]);
for(int j=0;j<m;j++)
{
if(tu[i][j]=='0') //存图中0;
{
book[i][j]=1;
b[i][j]=0;
now.x=i;
now.y=j;
now.step=0;
q.push(now);
}
}
}
bfs();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}
return 0;
}