HDOJ 2645 find the nearest station (BFS)

来源:互联网 发布:香港网络的英文缩写 编辑:程序博客网 时间:2024/06/05 10:15


http://acm.hdu.edu.cn/showproblem.php?pid=2645

find the nearest station

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 204    Accepted Submission(s): 112


Problem Description
Since dandelion has left the hometown so long,she finds it's difficult to find the station in the city.So she needs you ,a clear programmer, to help her.
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|.
 


Input
The input consists of several test cases. Each test case start with a line containing two number, n, m(1 <= n, m ≤ 182), the rows and the columns of city. Then n lines follow, each contain exact m characters, representing the type of block in it. (0 for empty place ,1 for station).The data will contains at least one station.
 


Output
For every case ,print a matrix with n rows and m columns, the number in the i row and j column stands for the distance from this grid to the shortest station.
 


Sample Input
3 4000100110110
 


Sample Output
3 2 1 02 1 0 01 0 0 1

以每个1点为起始进行BFS,找到最近的一个1,保存距离。

#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>using namespace std;const int NUM=200;struct Node{int x,y;} s,p,q;char graph[NUM][NUM];int num[NUM][NUM],dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}},r,c;int BFS(int xs,int ys){int i,map[NUM][NUM];memset(map,0,sizeof(map));queue<Node>Q;s.x=xs;s.y=ys;Q.push(s);map[s.x][s.y]=1;while(!Q.empty()){q=Q.front();Q.pop();for(i=0;i<4;i++){int X=q.x+dir[i][0];int Y=q.y+dir[i][1];if(X<0||X>=r||Y<0||Y>=c||map[X][Y]!=0) continue;map[X][Y]=map[q.x][q.y]+1;p.x=X;p.y=Y;Q.push(p);if(graph[X][Y]=='1')return map[X][Y]-1;}}}int main(){int i,j,map[NUM][NUM];while(~scanf("%d %d",&r,&c)){for(i=0;i<r;i++)scanf("%s",graph[i]);memset(map,0,sizeof(map));for(i=0;i<r;i++) for(j=0;j<c;j++) { if(graph[i][j]=='0') map[i][j]=BFS(i,j); }for(i=0;i<r;i++){for(j=0;j<c;j++){  printf("%d",map[i][j]);  if(j!=c-1)  printf(" ");    }    printf("\n");}}return 0;}

0 0
原创粉丝点击