Hihocode - 1478 Q - 水路距离
题目链接:https://cn.vjudge.net/problem/HihoCoder-1478
题目
给定一个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个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。
Sample Input
4 4
0110
1111
1111
0110
Sample Output
0 1 1 0
1 2 2 1
1 2 2 1
0 1 1 0
一道让我LTE到怀疑人生的题,
正解就是:把所有的水域都储存到队列中,然后你再对它进行BFS,那么第一次进队列的距离为0,依次在0点附近的满足条件的就为1,以次就可以达到目的,同时对数组进行标记。
主要就是一开始把所有水域都要进队列(奈何我没想到)。。。。
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
using namespace std;
char mp[805][805];
int v[805][805];
int w[805][805];
int n,m;
struct zxc
{
int x,y,s;
} st,en;
queue<zxc>q;
int main()
{
while(~scanf("%d %d",&n,&m))
{
memset(v,0,sizeof(v));
memset(w,0,sizeof(w));
while(!q.empty())
{
q.pop();
}
for(int i=0; i<n; i++)
{
scanf("%s",&mp[i]);
for(int j=0; j<m; j++)
{
if(mp[i][j]=='0')
{
st.x=i;
st.y=j;
st.s=0;
w[i][j]=0;
v[i][j]=1;
q.push(st);
}
}
}
int mv[4][2]= {1,0,-1,0,0,1,0,-1};
while(!q.empty())
{
st=q.front();
q.pop();
for(int i=0; i<4; i++)
{
en.x=st.x+mv[i][0];
en.y=st.y+mv[i][1];
if(en.x>=0&&en.x<n&&en.y>=0&&en.y<m&&v[en.x][en.y]==0)
{
en.s=st.s+1;
w[en.x][en.y]=en.s;
q.push(en);
v[en.x][en.y]=1;
}
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<m-1; j++)
{
printf("%d ",w[i][j]);
}
printf("%d\n",w[i][m-1]);
}
}
return 0;
}