uva 532 - Dungeon Master

bfs在三维空间的扩展,仔细一点问题不大。

 

#include<stdio.h>
#include<string.h>

typedef struct Point {
	int x;
	int y;
	int z;
	int len;
} Point;

typedef Point* Ptr;

char dungeon[40][40][40];
int l, r, c;
int dir[6][3] = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0,
		1 }, { 0, 0, -1 } };

Point start;
Point end;
Point queue[100000];
int length;

int bfs() {
	int front = 0;
	int rear = 1;
	queue[0].x = start.x;
	queue[0].y = start.y;
	queue[0].z = start.z;
	queue[0].len = start.len;
	dungeon[start.x][start.y][start.z] = '#';

	int i, newX, newY, newZ;
	while (front < rear) {
		Ptr p = &queue[front++];

		for (i = 0; i < 6; i++) {
			newX = p->x + dir[i][0];
			newY = p->y + dir[i][1];
			newZ = p->z + dir[i][2];
			if (newX >= 0 && newX < l && newY >= 0 && newY < r && newZ >= 0
					&& newZ < c && dungeon[newX][newY][newZ] != '#') {

				if (newX == end.x && newY == end.y && newZ == end.z) {
					return p->len + 1;
				}
				queue[rear].x = newX;
				queue[rear].y = newY;
				queue[rear].z = newZ;
				queue[rear].len = p->len + 1;
				dungeon[newX][newY][newZ] = '#';
				rear++;

			}

		}

	}
	return -1;
}

int main() {

	while (scanf("%d%d%d", &l, &r, &c) != EOF) {
		if (l == 0)
			break;
		length = -1;
		memset(dungeon, 0, sizeof(dungeon));

		getchar();
		int i, j, k;
		for (i = 0; i < l; i++) {
			for (j = 0; j < r; j++) {
				for (k = 0; k < c; k++) {
					scanf("%c", &dungeon[i][j][k]);
					if (dungeon[i][j][k] == 'S') {
						start.x = i;
						start.y = j;
						start.z = k;
						start.len = 0;
					} else if (dungeon[i][j][k] == 'E') {
						end.x = i;
						end.y = j;
						end.z = k;
						end.len = -1;
					}

				}
				getchar();
			}
			getchar();
		}

		length = bfs();
		if (length >= 0)
			printf("Escaped in %d minute(s).\n", length);
		else
			printf("Trapped!\n");

	}

	return 0;
}

 

你可能感兴趣的:(master)