题目链接:Click here
题意:天使被困在监狱,他的朋友们想救他,给定监狱,包括路(用点标示),墙(用#标示),天使的位置(用a标示),他的朋友(用r标示),监狱里还有守卫(用x标示),他的朋友只能向左右上下四个方向走,走一步花一单位时间,若碰上守卫,消灭守卫需要额外花费一单位时间。问最少多长时间天使能见到他的朋友。
思路:注意是朋友“们”,证明不止有一个朋友,为了时间最短,可以从天使逆着往朋友的方向走,找到的第一个朋友所耗费的时间是最小的。
开始便会想到BFS, 看了一些大神,还可以用DFS,自己也试了一下。
BFS:
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
struct node
{
int x, y;
int step;
};
queue<node> q;
int N, M, f, sx, sy, vis[202][202];
char map[202][202];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1,};
int check(int x, int y)
{
if(x < 0 || x >= N || y < 0 || y >= M)
return 0;
else
return 1;
}
void BFS()
{
while(!q.empty())
q.pop();
node s, e;
memset(vis, 0, sizeof(vis));
s.step = 0;
s.x = sx;
s.y = sy;
q.push(s);
vis[s.x][s.y] = 1;
while(!q.empty())
{
s = q.front();
q.pop();
if(map[s.x][s.y] == 'a')
{
cout << s.step << endl;
f =1;
}
if(map[s.x][s.y] == 'x')
{
map[s.x][s.y] = '.';
s.step += 1;
q.push(s);
continue;
}
for(int i = 0; i < 4; i++)
{
e.x = s.x + dx[i];
e.y = s.y + dy[i];
if(!check(e.x, e.y) || vis[e.x][e.y] || map[e.x][e.y] == '#')
continue;
e.step = s.step + 1;
q.push(e);
vis[e.x][e.y] = 1;
}
}
}
int main()
{
while(scanf("%d%d", &N, &M) != EOF)
{
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
{
cin >> map[i][j];
if(map[i][j] == 'r')
{
sx = i;
sy = j;
}
}
f = 0;
BFS();
if(!f)
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
DFS:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int u, v, sx, sy, ans;
char mapp[205][205];
int vis[205][205];
void DFS(int x, int y, int len)
{
if(x < 0 || y < 0 || x >= u || y >= v) return;
if(len >= ans) return;
if(mapp[x][y] == '#')return;
if(vis[x][y] == 1) return;
if(mapp[x][y] == 'r')
{
if(len < ans)
ans = len;
return;
}
if(mapp[x][y] == 'x')len++;
vis[x][y] = 1;
DFS(x+1, y, len+1);
DFS(x-1, y, len+1);
DFS(x, y+1, len+1);
DFS(x, y-1, len+1);
vis[x][y] = 0;
}
int main()
{
int len;
while(scanf("%d%d", &u, &v) != EOF)
{
memset(mapp, '#', sizeof(mapp));
for(int i = 0; i < u; i++)
{
for(int j = 0; j < v; j++)
{
cin >> mapp[i][j];
if(mapp[i][j] == 'a')
{
sx = i;
sy = j;
}
}
getchar();
}
ans = 1000000;
len = 0;
DFS(sx, sy, len);
if(ans != 1000000)
printf("%d\n", ans);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}