广度搜索bfs (杭电)

1.杭电1026 Ignatius and the Princess I

1.优先队列 按时间优先 时间小的先出队列 可以使英雄更快的救出公主
2.最后输出的时候 采用递归

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue> 
using namespace std;
struct points{
	int x;//这里的x相对于是坐标轴的x 也就是数组的列 
	int y;//这里的y相对于是坐标轴的y 也就是数组的行
	int count;
	friend bool operator<(points a,points b){//优先队列,按时间来 时间小的先出队列 
		return a.count>b.count;
	}
};
char map[100][100];
points flag[100][100];//它的count是map数组的每个地方的时间值,x和y是它上一步的位置 
int direction[2][4]={1,0,-1,0,0,1,0,-1};//右,下,左,上 
int n,m;
int bfs(int &count){
	priority_queue<points> qu;
	int tx,ty;
	while(!qu.empty()){
		qu.pop();
	}
	points start,tmp;
	start.x=0;start.y=0;start.count=0;
	qu.push(start);
	while(!qu.empty()){
		tmp=qu.top();
		qu.pop();
		if(tmp.x==(m-1)&&tmp.y==(n-1)){//找到出口 
			count = tmp.count;
			return 1;
		}
		for(int i=0;i<4;i++){//将四个方向 
			tx=tmp.x+direction[0][i];
			ty=tmp.y+direction[1][i];
			if(tx<0||ty<0||tx>=m||ty>=n||map[ty][tx]=='X'){
				continue;
			}
			start.x=tx;start.y=ty;start.count=tmp.count+1;
			flag[ty][tx]=tmp;
			flag[ty][tx].count=0;
			if(map[ty][tx]>'0'&& map[ty][tx]<'10') {
				start.count+=map[ty][tx]-'0';
				flag[ty][tx].count=map[ty][tx]-'0';
			}
			qu.push(start);
			map[ty][tx]='X';//这个格子走过了就封掉,因为如果再走这个格子时间会花更久 
		}
	}
	return 0;
}
void display(int count, int x,int y){//输出结果 
	if(count==0)return;
	count-=flag[x][y].count;
	display(count-1,flag[x][y].y,flag[x][y].x);
	cout<<count++<<"s:("<<flag[x][y].y<<","<<flag[x][y].x<<")->("<<x<<","<<y<<")"<<endl;
	while (flag[x][y].count--)
		cout << count++ << "s:FIGHT AT (" << x << "," << y << ")" << endl;
}
int main()
{
	while(cin>>n>>m){
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>map[i][j];
			}
		}
		int count=0;
		memset(flag,0,sizeof(flag));
		int result=bfs(count);
		if(result){
			cout<<"It takes "<<count<<" seconds to reach the target position, let me show you the way."<<endl;
			display(count,n-1,m-1);
		}
		else{
			cout<<"God please help our poor hero."<<endl;
		}
		cout<<"FINISH"<<endl;
	}
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值