HDU/HDOJ 1242 Rescue 典型的迷宫广度优先搜索题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

题目大意:在含有障碍的迷宫中求从一点到一点的最短时间或步数,这个题目有个坑爹的地方,天使的朋友不止一个,所以搜索的起点应该是从天使开始搜到朋友为止,最短路,还有一个坑爹的地方,题目求的是最短时间,不是最短步数,所以应该才用优先队列,小步数优先,结果我两种方法都试过,都能AC;

上代码:187MS 440K

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstdlib>
#include <fstream>
#include <queue>
using namespace std;

struct node{
	int x,y,step;
};
/*
bool operator<(node a,node b){
	return a.step > b.step;
}*/
queue<node> Q;
//priority_queue<node> Q;
bool visit[210][210];
char maze[210][210];
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
int sum,m,n,sx,sy,endx,endy;
bool isbound(int a,int b){
	if(a<1 || a>m || b<1 || b>n)return true;
	return false;
}
void bfs(){
	node p,q;
	p.x=sx;
	p.y=sy;
	p.step=0;
	Q.push(p);
	while(!Q.empty())
	{
		p=Q.front();
		Q.pop();
		if(p.x==endx&&p.y==endy){cout<<p.step<<endl;return;}
		for(int i=0;i<4;i++)
		{
			q.x=p.x+dir[i][0];
			q.y=p.y+dir[i][1];
		
			if(isbound(q.x,q.y))continue;//边界 
			if(maze[q.x][q.y]=='#')continue;//障碍 
			if(visit[q.x][q.y])continue; //判重 
			
			if(maze[q.x][q.y]=='.'||maze[q.x][q.y]=='r'){ //注意搜素方向 
				q.step=p.step+1;
				visit[q.x][q.y]=1;
				Q.push(q);
			}
			if(maze[q.x][q.y]=='x'){
				q.step=p.step+2;   //这是守卫的情况 
				visit[q.x][q.y]=1;
				Q.push(q);
			}
		}
	}
	cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
int main()
{
//	ifstream fin;
//	fin.open("data1.txt");
	while(cin>>m>>n)
	{
		while(!Q.empty())Q.pop();
		for(int i=1;i<=m;i++){
			for(int j=1;j<=n;j++){
				cin>>maze[i][j];
				if(maze[i][j]=='r'){
					endx=i;
					endy=j;
				}
				if(maze[i][j]=='a'){
					sx=i;
					sy=j;
				}
			}
		}
		memset(visit,0,sizeof(visit));
		visit[sx][sy]=1;
		bfs();
		
	}

	return 0;

}

 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值