Poj 2312 BFS+优先队列

题意:从Y走到T,B点要把它开枪消灭掉才能走,S和R不能走。

思路:BFS,将步数作为优先队列的关键字,E点直接一步走到,B点两步走到。

/*I have given up the treatment-_-||*/
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<algorithm>
#include<map>
using namespace std;
typedef long long LL;
const int maxn=310;
const int maxm=310;
const int inf=1e8;
const int mod=10000;
int n,m;
char mat[maxn][maxn];
int vis[maxn][maxn];
struct Node
{
	int x;
	int y;
	int step;
	bool operator < (const Node &tt) const {
        return step>tt.step;   //step小的在前面
    }
};
bool ok(int a,int b)
{
	if(a<1||b<1|a>n||b>m) return false;
	return true;
}
int bfs(Node s)
{
	memset(vis,0,sizeof(vis));
	vis[s.x][s.y]=1;
	int i,j;
	priority_queue<Node> que;
	que.push(s);
	while(!que.empty()){
		Node temp=que.top();
		que.pop();
		int a,b;
		a=temp.x;
		b=temp.y;
		//printf("*%d %d\n",a,b);
		if(ok(a-1,b)&&!vis[a-1][b]&&mat[a-1][b]!='S'&&mat[a-1][b]!='R'){
			Node tp;
			tp.x=a-1;
			tp.y=b;
			if(mat[a-1][b]=='T') return temp.step+1;
			else if(mat[a-1][b]=='E'){
				tp.step=temp.step+1;
				vis[a-1][b]=1;
				que.push(tp);
			}
			else{
				tp.step=temp.step+2;
				vis[a-1][b]=1;
				que.push(tp);
			}
		}
	    if(ok(a+1,b)&&!vis[a+1][b]&&mat[a+1][b]!='S'&&mat[a+1][b]!='R'){
			Node tp;
			tp.x=a+1;
			tp.y=b;
			if(mat[a+1][b]=='T') return temp.step+1;
			else if(mat[a+1][b]=='E'){
				tp.step=temp.step+1;
				vis[a+1][b]=1;
				que.push(tp);
			}
			else{
				tp.step=temp.step+2;
				vis[a+1][b]=1;
				que.push(tp);
			}
		}
		if(ok(a,b-1)&&!vis[a][b-1]&&mat[a][b-1]!='S'&&mat[a][b-1]!='R'){
			Node tp;
			tp.x=a;
			tp.y=b-1;
			if(mat[a][b-1]=='T') return temp.step+1;
			else if(mat[a][b-1]=='E'){
				tp.step=temp.step+1;
				vis[a][b-1]=1;
				que.push(tp);
			}
			else{
				tp.step=temp.step+2;
				vis[a][b-1]=1;
				que.push(tp);
			}
		}
		if(ok(a,b+1)&&!vis[a][b+1]&&mat[a][b+1]!='S'&&mat[a][b+1]!='R'){
			Node tp;
			tp.x=a;
			tp.y=b+1;
			if(mat[a][b+1]=='T') return temp.step+1;
			else if(mat[a][b+1]=='E'){
				tp.step=temp.step+1;
				vis[a][b+1]=1;
				que.push(tp);
			}
			else{
				tp.step=temp.step+2;
				vis[a][b+1]=1;
				que.push(tp);
			}
		}
	}
	return -1;
}
int main()
{
    //freopen ("in.txt" , "r" , stdin);
    //freopen ("output.txt" , "w" , stdout);
    int i,j;
    while(scanf("%d%d",&n,&m)&&(n||m)){
		for(i=1;i<=n;i++){
			scanf("%s",mat[i]+1);
		}
		Node start;
		Node target;
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++){
				if(mat[i][j]=='Y'){
					start.x=i;
					start.y=j;
					start.step=0;
					break;
				}
			}
		}
		int ans=bfs(start);
		printf("%d\n",ans);
    }
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值