HDOJ 2645 find the nearest station BFS

find the nearest station

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 2   Accepted Submission(s) : 2

Font: Times New Roman | Verdana | Georgia

Font Size:

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 4
0001
0011
0110

Sample Output

3 2 1 0
2 1 0 0
1 0 0 1
#include <iostream>
#include <queue>
using namespace std;
char map[2000][205];
int vis[2000][205];
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}}; 
int m,n,i,j;

struct node 
{
	int x,y;
	int cnt;
};
bool legel(int x,int y)
{
	if(x<1||x>m||y<1||y>n)
		return false;
	else return true;
}

int bfs(int x,int y)
{
	queue<node> q;
	node temp,temp1;
	temp.x=x;
	temp.y=y;
	temp.cnt=0;
	int x1,y1,x2,y2,i,cnt; //  cnt记录所走的步数
	q.push(temp);
	while(!q.empty())
	{
		temp=q.front();
		q.pop();
		x1=temp.x;
		y1=temp.y;
		cnt=temp.cnt;
		for(i=0;i<4;i++)
		{
			x2=x1+dir[i][0];
			y2=y1+dir[i][1];
			if(legel(x2,y2)==false)   //判断合法性
				continue;
			if(map[x2][y2]=='1')
				return cnt+1;
			else 
			{
				temp1.cnt=temp.cnt+1;
				temp1.x=x2;
				temp1.y=y2;
				q.push(temp1);
			}
		}
	}
	return -1;
}


int main()
{
	while(cin>>m>>n)
	{
		for(int i=1;i<=m;i++)
			for(int j=1;j<=n;j++)
				cin>>map[i][j];

		for(i=1;i<=m;i++)   // 对于每一个点,如果不是1则进行bfs找到最近距离的1并返回
			for(j=1;j<=n;j++)
			{
				if(map[i][j]=='1') 
					vis[i][j]=0;
				else
					vis[i][j]=bfs(i,j);
			}
		for(i=1;i<=m;i++)
		{
			for(j=1;j<=n;j++)
			{
				cout<<vis[i][j];
				if(j!=n) cout<<" ";
			}
			cout<<endl;
		}
	}
} 

你可能感兴趣的:(input,each,Matrix,output,distance)