find the nearest station
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 411 Accepted Submission(s): 245
Now you know the map of the city, which has showed every station in the city.You are asked to find the shortest distance between every grid and the stations.You should notice that the road in dandelion's hometown is vertical or horizontal,so the distance of two girds is defined as |x1-x2|+|y1-y2|.
3 4 0001 0011 0110
3 2 1 0 2 1 0 0 1 0 0 1
AC代码:
#include<stdio.h>
#include<cstdio>
#include<string.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int x,y,step;
};
int n,m;
char map[190][190];
int ans[190][190],vis[190][190];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int bfs(int x,int y)
{
queue<node>q;
memset(vis,0,sizeof(vis));
node a;
a.x=x,a.y=y,a.step=0;
q.push(a);
while(!q.empty())
{
node b;
b=q.front();
q.pop();
vis[b.x][b.y]=1;
if(map[b.x][b.y]=='1')
{
return b.step;
}
for(int i=0;i<4;i++)
{
node c;
c=b;
c.x+=dir[i][0];
c.y+=dir[i][1];
c.step++;
if(vis[c.x][c.y]==0&&c.x<n&&c.y>=0&&c.y<m)
{
q.push(c);
vis[c.x][c.y]=1;
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
ans[i][j]=bfs(i,j);
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m-1;j++)
{
printf("%d ",ans[i][j]);
}
printf("%d\n",ans[i][m-1]);
}
}
return 0;
}