uva 532 Dungeon Master

来源:互联网 发布:淘宝神笔在哪 编辑:程序博客网 时间:2024/05/19 02:27

bfs+优先队列找最短路径

#include <stdio.h>#include <queue>#include <vector>#include <algorithm>#include <functional>#include <string.h>using namespace std;#defineMAX35char arr[MAX][MAX][MAX];int step[MAX][MAX][MAX];char buffer[MAX];int start_l, start_i, start_j;int end_l, end_i, end_j;int ll, mm, nn;struct pos{int l;int i;int j;};bool operator < (const struct pos &a, const struct pos &b){return step[a.l][a.i][a.j] > step[b.l][b.i][b.j];}priority_queue< struct pos, vector<struct pos>, less<struct pos> > q;bool check(int l, int i, int j){if( !(l>=1&&l<=ll) )return false;if( !(i>=1&&i<=mm) )return false;if( !(j>=1&&j<=nn) )return false;if(arr[l][i][j] == '#')return false;if(step[l][i][j] > 0)return false;return true;}void bfs(int l, int i, int j){while(!q.empty())q.pop();struct pos p;memset(step[0][0], 0, MAX*MAX*MAX*sizeof(int));p.l = l; p.i = i; p.j = j;q.push(p);step[p.l][p.i][p.j] = 1;bool f;f = false;while(!q.empty()){l = q.top().l; i = q.top().i; j = q.top().j;q.pop();//printf("l=%d i=%d j=%d\n", l, i, j);if(l==end_l && i==end_i && j==end_j){f = true;break;}if(check(l-1, i, j)){ step[l-1][i][j]=step[l][i][j]+1; p.l=l-1; p.i=i; p.j=j; q.push(p); }if(check(l+1, i, j)){ step[l+1][i][j]=step[l][i][j]+1; p.l=l+1; p.i=i; p.j=j; q.push(p); }if(check(l, i-1, j)){ step[l][i-1][j]=step[l][i][j]+1; p.l=l; p.i=i-1; p.j=j; q.push(p); }if(check(l, i+1, j)){ step[l][i+1][j]=step[l][i][j]+1; p.l=l; p.i=i+1; p.j=j; q.push(p); }if(check(l, i, j-1)){ step[l][i][j-1]=step[l][i][j]+1; p.l=l; p.i=i; p.j=j-1; q.push(p); }if(check(l, i, j+1)){ step[l][i][j+1]=step[l][i][j]+1; p.l=l; p.i=i; p.j=j+1; q.push(p); }}if(f)printf("Escaped in %d minute(s).\n", step[end_l][end_i][end_j]-1);elseprintf("Trapped!\n");}void func(){int l, i, j;for(l=1; l<=ll; l++)for(i=1; i<=mm; i++)for(j=1; j<=nn; j++){if(arr[l][i][j] == 'S'){ start_l=l; start_i=i; start_j=j; }if(arr[l][i][j] == 'E'){ end_l=l; end_i=i; end_j=j; }}/*printf("%d %d %d\n", start_l, start_i, start_j);printf("%d %d %d\n", end_l, end_i, end_j);*/bfs(start_l, start_i, start_j);}int main(void){int l, m, n;int i, j;//freopen("input.dat", "r", stdin);while(1){scanf("%d %d %d", &l, &m, &n);getchar();if(!l && !m && !n)break;for(i=1; i<=l; i++){for(j=1; j<=m; j++){gets(arr[i][j]+1);}gets(buffer);}ll = l; mm = m; nn = n;func();}return 0;}


原创粉丝点击