标签:hdu
Description
Input
Output
Sample Input
7 8 #.#####. #.a#..r. #..#x... ..#..#.# #...##.. .#...... ........
Sample Output
13
题目大意:
你的朋友被抓进监狱,现在你要找到你的朋友,在途中你会遇到墙(’#‘),不能走,路(‘.’)可以走,花时为1秒,士兵(‘X’),花时间为2秒,求最短时间。
解题思路:
BFS和DP,不能单纯的只用BFS,因为有的一步是要花时间2,有的为1,不能确保当前的就是最优的,所有有要用到DP。
代码;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct node{
int i,j;
node(int i0=0,int j0=0){
i=i0,j=j0;
}
};
const int dirJ[4]={0,1,0,-1};
const int dirI[4]={1,0,-1,0},maxN=220;
int n,m,is,js,ie,je,time[maxN][maxN];
char str[maxN][maxN];
void bfs(){
queue <node> path;
time[is][js]=0;
path.push(node(is,js));
while(!path.empty()){
node s=path.front();
path.pop();
for(int k=0;k<4;k++){
int di=s.i+dirI[k],dj=s.j+dirJ[k];
if(di>=n||dj>=m||di<0||dj<0) continue;
if(str[di][dj]=='#') continue;
int tmp=time[s.i][s.j]+1;
if(str[di][dj]=='x') tmp++;
if( tmp<time[di][dj] || time[di][dj]==-1 ){//带点dp优化.
path.push(node(di,dj));
time[di][dj]=tmp;
}
}
}
if(time[ie][je]==-1) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",time[ie][je]);
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
memset(time,-1,sizeof(time));
for(int i=0;i<n;i++){
scanf("%s",str[i]);//建议这样。
for(int j=0;j<m;j++){
if(str[i][j]=='r'){is=i,js=j;}
if(str[i][j]=='a'){ie=i,je=j;}
}
}
bfs();
}
return 0;
}
HDU 1242 Rescue(求最短时间救出同伴,BFS+DP)
标签:hdu
原文地址:http://blog.csdn.net/hush_lei/article/details/38927159