1题目编号:1012
2 题目内容:
7 8<br>#.#####.<br>#.a#..r.<br>#..#x...<br>..#..#.#<br>#...##..<br>.#......<br>........<br>
13<br>
3 解题思路形成过程:BFS。之前理解错题意,以为每次只有一个‘r’,所以WA了,后来想起了上周上课讲的例题,和这个题非常相似,思路也应该是一样的,即可以有多个‘r’的,这样按原来把‘r’作为起始点开始搜索的思路就错误了,因为不知道从哪个‘r’开始会取得最短时间,而且多个‘r’储存和操作起来也比较麻烦,所以后来换了一个思路:如果某一个r能找到a,那么a一定能找到这个r 。这样以来我们不必从多个r同时出发去找a,可以直接让a去找离他最近的就行了!按照这思路就容易多了…
4 代码:#include<stdio.h>
#include<queue>
using namespace std;
typedef struct
{
int i, j, time;
}point;
int n, m;
int dir[4][2] = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
char map[201][201];
point start;
int bfs(point start)
{
queue<point>q;
int i;
point cur, next;
start.time = 0;
map[start.i][start.j] = '#';
q.push(start);
while (!q.empty())
{
cur = q.front();
q.pop();
for (i = 0; i<4; i++)
{
next.i = cur.i + dir[i][0];
next.j = cur.j + dir[i][1];
if (map[next.i][next.j] == 'r')
{
return cur.time + 1;
}
if (next.i >= 0 && next.i<n&&next.j >= 0 && next.j<m)
if (map[next.i][next.j] != '#')
{
if (map[next.i][next.j] == 'x')
{
map[next.i][next.j] = '#';
next.time = cur.time + 2;
q.push(next);
}
else
{
map[next.i][next.j] = '#';
next.time = cur.time + 1;
q.push(next);
}
}
}
}
return -1;
}
int main()
{
int i, j;
while (scanf("%d %d", &n, &m) != EOF)
{
getchar();
bool flag = true;
for (i = 0; i<n; i++)
{
for (j = 0; j<m; j++)
{
scanf("%c", &map[i][j]);
if (map[i][j] == 'a')
{
start.i = i;
start.j = j;
}
}
getchar();
}
int T = bfs(start);
if (T >= 0)
printf("%d\n", T);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}