您的位置:首页 > 其它

hdu1253 胜利大逃亡(三维bfs)

2016-02-27 13:08 316 查看
三维bfs,感觉搜索还很弱啊。。。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <stdlib.h>

using namespace std;

const int N = 52;
const int INF = 1000000;

int Map[52][52][52], visit[52][52][52];
int a, b, c, t;

struct Poi
{
int x, y, z;
int t;
};

int dir[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}, {0, -1, 0}};

int go(int x0, int y0, int z0)
{
if(x0 >= 0 && x0 < a && y0 >= 0 && y0 < b && z0 >= 0 && z0 < c && Map[x0][y0][z0] == 0) return 1;
else return 0;
}

int BFS(int m)
{
Poi st, ed;
queue <Poi> q;
st.x = 0;
st.y = 0;
st.z = 0;
st.t = 0;
q.push(st);
memset(visit, 0, sizeof(visit));
visit[0][0][0] = 1;
while(!q.empty())
{
st = q.front();
q.pop();
if(st.t > m) return -1;
if(st.x == a - 1 && st.y == b - 1 && st.z == c - 1 && st.t <= m) return st.t;
for(int i = 0; i < 6; i ++)
{
ed.x = st.x + dir[i][0];
ed.y = st.y + dir[i][1];
ed.z = st.z + dir[i][2];
if(go(ed.x, ed.y, ed.z) && !visit[ed.x][ed.y][ed.z])
{
visit[ed.x][ed.y][ed.z] = 1;
ed.t = st.t + 1;
if(abs(a - (ed.x + 1)) + abs(b - (ed.y + 1)) + abs(c - (ed.z + 1)) + ed.t > m) continue; //剪枝预判
q.push(ed);
}
}
}
return -1;
}
int main()
{
// freopen("in.txt", "r", stdin);
int n, i, j, k, t;
scanf("%d", &n);
while(n --)
{
scanf("%d%d%d%d", &a, &b, &c, &t);
for(i = 0; i < a; i ++)
for(j = 0; j < b; j ++)
for(k = 0; k < c; k ++)
scanf("%d", &Map[i][j][k]);
printf("%d\n", BFS(t));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu