本题需要注意的是,天使的朋友可能不只一个,所以,应该从天使的位置开始搜去找其朋友就可以了。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#define N 220
using namespace std;
char a[N][N];
int vis[N][N];
int n,m, sx, sy;
int ans, flag;
int path[4][2] = {{1,0},{0,1},{0,-1},{-1,0}};
/**
本题需要注意的是,天使的朋友可能不只一个,所以,应该从天使的位置开始搜去找其朋友就ok了。
*/
int check(int x, int y)
{
if(x < 0 || x >= n || y < 0 || y >= m) return 0;
if(a[x][y] == '#' || vis[x][y]) return 0;
return 1;
}
void dfs(int x, int y, int cnt)
{
if(cnt > ans) return; //剪枝
if(a[x][y] == 'r' && cnt < ans)
{
ans = cnt;
flag = 1;
return;
}
for(int i = 0;i < 4;i++)
{
int nx = x + path[i][0];
int ny = y + path[i][1];
if(check(nx, ny))
{
vis[nx][ny] = 1;
if(a[nx][ny] == 'x')
dfs(nx, ny, cnt+2);
else dfs(nx, ny, cnt+1);
vis[nx][ny] = 0;
}
}
}
int main()
{
while(~scanf("%d%d", &n,&m))
{
for(int i = 0;i < n;i++)
{
for(int j = 0;j < m;j++)
{
scanf(" %c", &a[i][j]);
if(a[i][j] == 'a')
{
sx = i; sy = j;
}
}
}
ans = 0xfffff;
flag = 0;
vis[sx][sy] = 1;
dfs(sx, sy, 0);
if(flag)
printf("%d\n", ans);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}