uva 532 Dungeon Master

bfs+优先队列找最短路径

#include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
#include <string.h>
using namespace std;

#define		MAX		35

char 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);
	else
		printf("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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值