POJ 2251 Dungeon Master

题目链接:Dungeon Master

解题思路:从二维转化成了三维,用BFS,注意图的录入方式。(用STL的队列实现)

#include<stdio.h>
#include<string.h>
#include<queue>
#define MAX 35

using namespace std;

struct A{
	int x, y, z, time;
};
typedef struct A node;

char map[MAX][MAX][MAX];
int v[MAX][MAX][MAX];
const int dir[6][3] = {0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 1, 0, 0, -1, 0, 0};
int l, r, c, ans;
int sx, sy, sz, ex, ey, ez;

int judge(int x, int y, int z){
	if(map[z][x][y] == '#' || v[z][x][y] || z <= 0 || x <= 0 || y <= 0 || z > l || x > r || y > c){
		return 0;
	}
	return 1;
} 

int BFS(){
	queue<node> my;
	node s, tem;
	int i;
	tem.x = sx;tem.y = sy;tem.z = sz;tem.time = 0;
	v[sz][sx][sy] = 1;
	my.push(tem);
	while(!my.empty()){
		s = my.front();
		my.pop();
		for(i = 0; i < 6; i++){
			int z = s.z + dir[i][0];
			int x = s.x + dir[i][1];
			int y = s.y + dir[i][2];
			if(judge(x, y, z)){
				if(x == ex && y == ey && z == ez){
					return s.time + 1;
				}
				tem.x = x;tem.y = y;tem.z = z;tem.time = s.time + 1;
				my.push(tem);
				v[z][x][y] = 1;
			}
		}
	}
	return -1;
}

int main(){
	int i, j, k;
	//freopen("in.txt", "r", stdin);
	while(scanf("%d%d%d", &l, &r, &c) != EOF){
		if(!l && !c && !r)		return 0;
		memset(v, 0, sizeof(v));
		//ans = -1;
		getchar();
		for(i = 1; i <= l; i++){
			for(j = 1; j <= r; j++){
				for(k = 1; k <= c; k++){
					scanf("%c", &map[i][j][k]);
					if(map[i][j][k] == 'S'){
						sx = j;sy = k;sz = i;
					}
					if(map[i][j][k] == 'E'){
						ex = j;ey = k;ez = i;
					}
				}
				getchar();
			}
			getchar();
		}
		ans = BFS();
		if(ans == -1){
			printf("Trapped!\n");
		}
		else{
			printf("Escaped in %d minute(s).\n", ans);
		}
	}  
	return 0;
}


 

你可能感兴趣的:(POJ 2251 Dungeon Master)