hdu2645 find the nearest station(BFS)

题意:给一个图你,问图中每一个0和最近的1的距离

思路:直接暴力BFS...


#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 330
#define LL long long
int cas=1,T;
int n,m;
char mapp[maxn][maxn];
int d[maxn][maxn],vis[maxn][maxn];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct Node
{
	int x,y;
};
bool check(int x,int y)
{
	if (x<0 || x>=n || y<0 || y>=m ||vis[x][y])
		return false;
	return true;
}
int main()
{
	while (scanf("%d%d",&n,&m)!=EOF)
	{
        memset(d,0,sizeof(d));
		memset(vis,0,sizeof(vis));
		Node s;
		queue<Node> q;
		for (int i = 0;i<n;i++)
		{
			scanf("%s",mapp[i]);
			for (int j = 0;j<m;j++)
			{
				if (mapp[i][j] == '1')
				{
                    s.x=i;
					s.y=j;
					q.push(s);
					vis[i][j]=1;
				}
			}
		}

		while (!q.empty())
		{
			s=q.front();q.pop();
			for (int i = 0;i<4;i++)
			{
				Node temp;
                temp.x = s.x+dir[i][0];
				temp.y = s.y+dir[i][1];
				if (!check(temp.x,temp.y))
					continue;
				q.push(temp);
				vis[temp.x][temp.y]=1;
				d[temp.x][temp.y] = d[s.x][s.y]+1;
			}
		}

		for (int i =0;i<n;i++)
		{
			printf("%d",d[i][0]);
			for (int j = 1;j<m;j++)
				printf(" %d",d[i][j]);
			printf("\n");
		}
	}
	//freopen("in","r",stdin);
	//scanf("%d",&T);
	//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
	return 0;
}


题目

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
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值