第一次用容器做的BFS题目,题目有个地方比较坑,就是遍历时的方向,比如上下左右能AC,右上左下就WA
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
char map[205][205];
int x_begin,y_begin,flag,n,m;
int v[205][205],d[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
struct node
{
int x;
int y;
int step;
};
void bfs()
{
queue <node> q;
node s,temp;
s.x = x_begin;
s.y = y_begin;
s.step = 0;
v[x_begin][y_begin] = 0;
q.push(s);
while(!q.empty())
{
temp = q.front();
q.pop();
if(map[temp.x][temp.y] == 'r')
{
printf("%d\n",temp.step);
flag = 1;
return ;
}
for(int i = 0 ; i < 4 ; i ++)
{
s = temp;//temp为本次遍历的结点
s.x += d[i][0];
s.y += d[i][1];
if(s.x >= 0 && s.x < n && s.y >= 0 && s.y < m && map[s.x][s.y] != '#')
{
if(map[s.x][s.y] == 'x')//杀一个守卫时间+2
s.step += 2;
else
s.step ++;
if(v[s.x][s.y] >= s.step)
{
v[s.x][s.y] = s.step;
q.push(s);
}
}
}
}
}
int main()
{
int i,j;
while(~scanf("%d%d",&n,&m))
{
for(i = 0 ; i < n ; i ++)
{
scanf("%s",map[i]);
for(j = 0 ; j < m ; j ++)
if(map[i][j] == 'a')
{
x_begin = i;
y_begin = j;
}
}
memset(v,1,sizeof(v));
flag = 0;
bfs();
if(!flag)
printf("Poor ANGEL has to stay in the * all his life.\n");
}
return 0;
}