題目鏈接:Rescue
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
//行列及最少時(shí)間
int m, n, res;
//存儲區(qū)域
char map[201][201];
//四個(gè)方向
int ds[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
//深度優(yōu)先搜索算法求取最短時(shí)間
//根據(jù)題意立镶,angle的朋友可能有多個(gè),因此可利用反向思維服傍,從angle出發(fā)去尋找朋友
void dfs(int x, int y, int time){
int i, dx, dy;
//遍歷四個(gè)方向
for(i = 0; i < 4; i++){
dx = ds[i][0] + x;
dy = ds[i][1] + y;
//確定未超過邊界
if(dx >= 0 && dx < m && dy >= 0 && dy < n){
//遇到衛(wèi)兵時(shí)努潘,如果時(shí)間加2(1份走到這廊鸥,一份殺死衛(wèi)兵)比當(dāng)前的時(shí)間小,則繼續(xù)搜索
if(map[dx][dy] == 'x' && time + 2 < res){
map[dx][dy] = '#';
dfs(dx, dy, time+2);
//搜索完后,設(shè)置回原來的狀態(tài)幢妄,方便其他搜索線路進(jìn)行 剧董,從而能找到最短時(shí)間
map[dx][dy] = 'x';
}
//遇到路
else if(map[dx][dy] == '.' && time + 1 < res){
map[dx][dy] = '#';
dfs(dx, dy, time+1);
map[dx][dy] = '.';
}
//遇到朋友
else if(map[dx][dy] == 'r'){
res = (time+1) < res ? time+1:res;
return ;
}
}
}
}
int main()
{
int i, j, ix, iy;
while(scanf("%d%d", &m, &n) != EOF){
res = 10000;
getchar();
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
scanf("%c", &map[i][j]);
//記錄angle的位置
if(map[i][j] == 'a'){
ix = i;
iy = j;
}
}
getchar();
}
dfs(ix, iy, 0);
if(res != 10000)
printf("%d\n", res);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}