您的位置:首页 > 产品设计 > UI/UE

hdu 1242 Rescue (bfs)

2014-07-28 15:45 399 查看
小记:太不应该了。我想到了步数少到达一个搜过的点,那么这个点就应该重新搜,但是在结尾的时候,我居然天真的设置成了,一碰到a就输出时间,以为那就是答案。

思路:bfs每一个r,然后记录到达某一点的最少时间,当时间更新即更小的时间出现时,就应该再入队。

因此,在碰到a时,我们不能直接判为答案,而是要到搜索结束,选取时间最小的那个碰到a的为答案。QAQ,wa了6,7次。

不过这样锻炼的是自己的思维,让自己对自己写的代码了解的更通彻,也可以逐步改正一些错误。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>

using namespace std;

#define mst(a,b) memset(a,b,sizeof(a))
#define REP(a,b,c) for(int a = b; a < c; ++a)
#define eps 10e-8

const int MAX_ = 1010;
const int N = 100010;
const int INF = 0x7fffffff;

struct Point {
int x, y;
int step;
}p2[MAX_*40], p1;

int dir[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
int vis[MAX_][MAX_];
int a[MAX_][MAX_], num[MAX_][MAX_];
int n, m;

char str[MAX_][MAX_];

int bfs(Point x)
{
queue<Point> q;
mst(vis, 0);
x.step = 0;
q.push(x);
vis[x.x][x.y] = 1;
int ans = INF;

while(!q.empty()){
Point cur = q.front(); q.pop();

if(cur.x == p1.x && cur.y == p1.y){
//printf("%d\n", cur.step);
ans = min(ans, cur.step);
//return cur.step;
}

REP(i,0,4){
Point nt;
nt.x = cur.x + dir[i][1];
nt.y = cur.y + dir[i][0];
nt.step = cur.step+1;

if((nt.x > -1 && nt.x < n) &&(nt.y > -1 && nt.y < m) ){
if((str[nt.x][nt.y] == 'x' || str[nt.x][nt.y] == '.' || str[nt.x][nt.y] == 'a')){
if(str[nt.x][nt.y] == 'x'){++nt.step;}

if(!vis[nt.x][nt.y]|| nt.step < vis[nt.x][nt.y]){
//printf("%d %d %d \n", nt.x, nt.y, nt.step);
vis[nt.x][nt.y] = nt.step;
q.push(nt);
}
}
}
}
}

return ans;
}

int main(){
int T, k, cnt;
while(~scanf("%d%d", &n, &m)){
cnt = 0;
REP(i, 0, n){
scanf("%s", str[i]);
REP(j, 0, m){
if(str[i][j] == 'r'){
p2[cnt].x = i; p2[cnt++].y = j;
}
else if(str[i][j] == 'a'){
p1.x = i; p1.y = j;
}
}
}
bool flag = 0;
int ans = INF;
REP(i, 0, cnt){
int tmp = bfs(p2[i]);
//printf("%d %d\n", tmp, vis[p2[i].x][p2[i].y]);
//if(tmp != -1)
ans = min(ans, tmp);
}
if(ans == INF)printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: