题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=284
ac代码:
#include<stdio.h>
#include<string.h>
#include<string>
#include<queue>
#include<iostream>
using namespace std;
int n,m,bx,by,bz,end;
int d[4][2]={0,1,0,-1,1,0,-1,0};
int v[300][300];//标记元素
char map[301][301];//地图
struct node
{
int x;
int y;
int num;
friend bool operator <(node a,node b)//定义优先级,步数少的优先
{
return a.num>b.num;
}
}now,temp;
int check(int a,int b)//判断
{
if(a>=n||a<0||b>=m||b<0||map[a][b]=='S'||map[a][b]=='R'||v[a][b])
return 0;
return 1;
}
void bfs()
{
priority_queue<node>q;//创建优先队列
now.x=bx;now.y=by;now.num=0;v[bx][by]=1;
q.push(now);
while(!q.empty())
{
temp=q.top();
q.pop();
for(int i=0;i<4;i++)
{
now.x=temp.x+d[i][0];
now.y=temp.y+d[i][1];
if(map[now.x][now.y]=='T')
{
bz=1;
end=temp.num+1;
return;
}
else if(check(now.x,now.y))
{
if(map[now.x][now.y]=='B')
now.num=temp.num+2;
else
now.num=temp.num+1;
v[now.x][now.y]=1;
q.push(now);
}
}
}
}
int main()
{
while((scanf("%d%d",&n,&m)!=EOF)&&(n||m))
{
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
for(int j=0;j<m;j++)
{
if(map[i][j]=='Y')//记录开始位置
{
bx=i;by=j;
}
}
}
memset(v,0,sizeof(v));
bz=0;
bfs();
if(bz)
printf("%d\n",end);
else
printf("-1\n");
}
return 0;
}