优先队列的简单应用
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
struct type
{
int x,y,step;
};
char s[350][350];
int m,n,dx[4]={-1,1,0,0},dy[4]={0,0,-1,1},ans,vis[350][350];
bool operator < (const type &a,const type &b) //记住用法
{
return a.step>b.step;
}
bool judge(int x,int y)
{
if(x<n&&x>=0&&y<m&&y>=0&&!vis[x][y]&&s[x][y]!='S'&&s[x][y]!='R')
return true;
return false;
}
int bfs(int x,int y)
{
int i,j;
type p;
priority_queue<type> q;
p.x=x;
p.y=y;
p.step=0;
q.push(p);
while(!q.empty())
{
p=q.top();
q.pop();
if(s[p.x][p.y]=='T')
return p.step;
for(i=0;i<4;i++)
{
int tx=p.x+dx[i],ty=p.y+dy[i];
if(judge(tx,ty))
{
vis[tx][ty]=1;
type tp;
tp.x=tx;
tp.y=ty;
tp.step=p.step+1;
if(s[tx][ty]=='B')
tp.step++;
q.push(tp);
}
}
}
return -1;
}
int main()
{
int i,j,sx,sy,ex,ey;
// freopen("test.txt", "r", stdin);
while(scanf("%d%d",&n,&m)&&(n||m))
{
getchar();
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)
gets(s[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(s[i][j]=='Y')
{
sx=i;
sy=j;
}
vis[sx][sy]=1;
printf("%d\n",bfs(sx,sy));
}
return 0;
}