hdoj 1242(这样写bfs才清晰,而且容易debug)

#include<iostream>
#include<stdio.h>
#include<string>
#include<queue>
using namespace std;
#define MAX 210
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};char map[MAX][MAX];
int mask[MAX][MAX];
class Point
{
public:
	int x;
	int y;
	int c;
};
Point s,e;int N,M;//N是行,M是列
int over(Point p)
{
	if(p.x<0||p.y<0)	return 1;
	if(p.x>=M||p.y>=N)	return 1;
	return 0;
}
void bfs()
{
	s.c=0;mask[s.x][s.y]=0;
	queue<Point>q;
	q.push(s);
	Point p,cs;int i;
	while(!q.empty())
	{
		p=q.front();q.pop();
		for(i=0;i<4;i++)
		{
			cs.x=p.x+dir[i][0];cs.y=p.y+dir[i][1];cs.c=p.c+1;
			if(over(cs)||map[cs.x][cs.y]=='#')
				continue;
			if(map[cs.x][cs.y]=='x')
				cs.c++;
			if(mask[cs.x][cs.y]==-1||cs.c<mask[cs.x][cs.y])
			{
				mask[cs.x][cs.y]=cs.c;
				q.push(cs);
			}

		}
	}
}
void init()
{
	int i,j;
	for(i=0;i<MAX;i++)
	{
		for(j=0;j<MAX;j++)
		{
			map[i][j]='0';
			mask[i][j]=-1;//标记没有访问
		}
	}
}
int main()
{
	//freopen("input.txt","r",stdin);
	while(scanf("%d%d",&N,&M)!=EOF)
	{
		//初始化
		init();

		//输入
		getchar();char temp[MAX];
		int i,j;
		for(i=0;i<N;i++)
		{
			gets(temp);
			for(j=0;j<M;j++)
			{
				map[j][i]=temp[j];
				//标记开始点
				if(map[j][i]=='r')
				{
					map[j][i]='.';
					s.x=j;s.y=i;
				}
				//标记结束点
				if(map[j][i]=='a')
				{
					map[j][i]='.';
					e.x=j;e.y=i;
				}
			}
		}


		//开始处理
		bfs();
        if(mask[e.x][e.y] == -1)
            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
        else
            cout<<mask[e.x][e.y]<<endl;
	}
}
/*
1	freopen("input.txt","r",stdin);
会导致wa,以后要注意
2   这个思路很清晰,以后就照这个写
3   queue只存在于bfs()当中,
4   bfs()中不能有return。因为如果说中文是全世界最美丽的语言,但是我现在只学啦中文,不能这样说
要把全部的语言都试一次才可以这样说。

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值