hdu1242

来源:互联网 发布:软件测试零基础 编辑:程序博客网 时间:2024/06/06 09:00

这道题的主要是意思是求从 r 到 a的最短路径

思路就是用优先队列+bfs:每次找出最短的路径,并向下扩展。

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
#define mx 210
char map[mx][mx];
int m,n;
struct node
{
int x;
int y;
int sum;
friend bool operator<(node s1,node s2)
{
return s1.sum>s2.sum;
}
}cx;


int cont;
int sx,sy;
int flag;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};


void bfs()
{
cont=0;
flag=-1;
     int i,j;
     priority_queue<node>ka;
node a,b;
  a.x=sx;
  a.y=sy;
       a.sum=1;
ka.push(a);
int ty,tx;
while(!ka.empty())
{
    cx=ka.top();
    ka.pop();
    for(i=0;i<4;i++)
    {
         tx=cx.x+dir[i][0];
         ty=cx.y+dir[i][1];
         if(tx>=0&&ty>=0&&tx<n&&ty<m&&map[tx][ty]!='#')
         {
         if(map[tx][ty]=='.')
         b.sum=cx.sum+1;
         else if(map[tx][ty]=='x')
         b.sum=cx.sum+2;   
        else if(map[tx][ty]=='a')
         {
            cont+=cx.sum;
         flag=0;
         return;
         }
         b.x=tx;
         b.y=ty;
         map[tx][ty]='#';
         ka.push(b);     
        }
      }
}
}
int main()
{
int f,g;
while(scanf("%d%d",&n,&m)!=EOF)
{
     for(f=0;f<n;f++)
{
      scanf("%s",map[f]);
for(g=0;g<m;g++)
{
  if(map[f][g]=='r')
  {
sx=f;
sy=g;
}
  }
  }
map[sx][sy]='#';  
bfs();
if(flag==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",cont);
}
}

0 0