POJ 2251 Dungeon Master (bfs)

//三维迷宫

//标准的bfs

#include <iostream>

#include <queue>

#include <memory.h>

using namespace std;



struct coordinate

{

	int x,y,z,step;

};



int L,R,C;

bool isvisited[31][31][31];

bool place[31][31][31];

coordinate goal;

coordinate start;

int times;

void bfs();

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



int main()

{

	char c;

	while (cin >> L >> R >> C && (L || R || C))

	{

		memset(place, true, sizeof(place));

		for (int i = 1; i <= L; i++) //z

		{

			for (int j = 1; j <= R; j++)//x

			{

				for (int k = 1; k <= C; k++)//y

				{

					cin >> c;

					if (c == 'E')

					{

						goal.x = j;

						goal.y = k;

						goal.z = i;

					}

					else if (c == 'S')

					{

						start.x = j;

						start.y = k;

						start.z = i;

					}

					else if (c == '#')

						place[j][k][i] = false;

				}

			}

		}



		bfs();

		

	}

	return 0;

}



void bfs()

{

	memset(isvisited, false, sizeof(isvisited));

	queue<coordinate> Q;

	coordinate p, tmp;

	start.step = 0;

	Q.push(start);

	isvisited[start.x][start.y][start.z] = true;



	while (!Q.empty())

	{

		tmp = Q.front();

		Q.pop();



		if (tmp.x == goal.x && tmp.y == goal.y && tmp.z == goal.z)

		{

			cout << "Escaped in " << tmp.step << " minute(s)." << endl;

			return ;

		}



		for (int i = 0; i < 6; i++)

		{

			p.x = tmp.x + dir[i][0];

			p.y = tmp.y + dir[i][1];

			p.z = tmp.z + dir[i][2];

			p.step = tmp.step + 1;



			if (p.x > 0 && p.x <= R && p.y > 0 && p.y <= C && p.z > 0 && p.z <= L

			   && place[p.x][p.y][p.z]

			   && !isvisited[p.x][p.y][p.z])

			   {

				   isvisited[p.x][p.y][p.z] = true; 

				   Q.push(p);

			   }

		}		

	}

	cout << "Trapped!" << endl;

}

你可能感兴趣的:(master)