poj 2312 Battle City-bfs

题目自己看吧:http://poj.org/problem?id=2312

代码:

 

#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
#define INF 1000000001
struct Point{
	int x,y;
	int step;
};
//优先队列
bool operator<(const Point &a,const Point &b){
	return a.step>b.step; 
}
priority_queue<Point>Q;
Point turn,tes;
int m,n;
char map[310][310];
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
int bfs(){
	Point s,t;
	int i,xx,yy;
	while(!Q.empty()){
		Q.pop();
	}
	Q.push(turn);
	while(!Q.empty()){
		s=Q.top();
		Q.pop();
		for(i=0;i<4;i++){
			xx=s.x+dx[i];
			yy=s.y+dy[i];
			if(xx<0||yy<0||xx>=m||yy>=n||map[xx][yy]== 'R'||map[xx][yy]=='S'){
				continue;
			}
			if(xx==tes.x&&yy==tes.y)
				return s.step+1;
			t.x=xx;
			t.y=yy;
			if(map[xx][yy]=='B') t.step=s.step+2;
			else t.step=s.step+1;
			map[xx][yy]='R';
			Q.push(t);
		}
	}
	return -1;
}

int main(){
	while(scanf("%d%d",&m,&n)!=EOF&&(n+m)){
		for(int i=0;i<m;i++){
			scanf("%s",map[i]);
			for(int j=0;j<n;j++){
				if(map[i][j]=='Y'){
					turn.x=i;
					turn.y=j;
					turn.step=0;
				}
				else if(map[i][j]=='T'){
					tes.x=i;
					tes.y=j;
				}
			}
		}
		printf("%d\n" ,bfs());
	}
	return 0;
}

你可能感兴趣的:(poj 2312 Battle City-bfs)