首先总结一下广度优先搜索题目做题的几个主要掌握的
1.如何表示状态的变化,图中哪些是动的,哪些是不动的,用结构体去把状态简单的表示出来
typedef struct node{
int x,y;
int dis;
bool operator<(const node &e)const
{
return dis>e.dis;
}
};
这是这道题的状态表示,因为只有r是动的,用x,y表示r的位置,以及记录走的步数就行了
2. 题目如果有其他的最优要求,则要用优先队列;
3.进行状态转移的时候的一般条件限制有:越出图的大小,是否访问过,还有题目规定的不能访问的点;
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#include <queue>
#define maxn 1000
char map[maxn][maxn];
int vis[maxn][maxn];
int n,m;
int sx,sy;
int ex,ey;
int dir[4][2]={0,1,1,0,-1,0,0,-1};
typedef struct node{
int x,y;
int dis;
bool operator<(const node &e)const
{
return dis>e.dis;
}
};
node temp,s,next1;
int bfs()
{
priority_queue<node>que;
que.push(s);
while(!que.empty())
{
temp=que.top();
que.pop();
for(int i=0;i<4;i++)
{
int x1=temp.x+dir[i][0];
int y1=temp.y+dir[i][1];
if(vis[x1][y1])continue;
vis[x1][y1]=1;
if(x1>=n||x1<0||y1>=m||y1<0||map[x1][y1]=='#')
continue;
if(map[x1][y1]=='x')
next1.dis=temp.dis+2;
else
next1.dis=temp.dis+1;
if(map[x1][y1]=='a')
return next1.dis;
next1.x=x1;
next1.y=y1;
que.push(next1);
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
{
scanf("%s",map[i]);
for(int j=0;j<m;j++)
{
if(map[i][j]=='r')
{
sx=i;
sy=j;
}
if(map[i][j]=='a')
{
ex=i;
ey=j;
}
}
}
s.x=sx;
s.y=sy;
s.dis=0;
memset(vis,0,sizeof(vis));
vis[sx][sy]=1;
int ans=bfs();
if(ans==-1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n",ans);
}
}