uva532

3 篇文章 0 订阅
1 篇文章 0 订阅

对照着百度百科对广度搜索的解释 终于做出来了

#include<iostream>
#include<queue>
#include<cstdio>
#include<string.h>
using namespace std;

int strpArr[6][3] = { { 0, 0, 1 }, { 0, 0, -1 }, { 0, 1, 0 }, { 0, -1, 0 }, { 1, 0, 0 }, { -1, 0, 0 } };
char trap[30][30][30];
bool vis[30][30][30];
int m, n, k;
int a1, a2, a3, b1, b2, b3;//起点与终点
struct Node{
	int x, y, z;
	int step;
	Node(int a, int b, int c, int d) :x(a), y(b), z(c), step(d){}
};

int bfs();

int main(){
	while (cin >> m >> n >> k){
		memset(trap, 0, sizeof(trap));
		memset(vis, 0, sizeof(vis));
		if (m == 0 && n == 0 && k == 0)    break;
		for (int i = 0; i<m; i++){
			getchar();
			for (int j = 0; j<n; j++){
				gets(trap[i][j]);
			}
		}
		//计算起点与终点
		for (int i = 0; i<m; i++){
			for (int j = 0; j<n; j++){
				for (int z = 0; z<k; z++){
					if (trap[i][j][z] == 'S')      a1 = i, a2 = j, a3 = z;
					if (trap[i][j][z] == 'E'){
						b1 = i, b2 = j, b3 = z;
					}
				}
			}
		}
		int ans = bfs();
		if (ans == 0)      cout << "Trapped!" << endl;
		else    cout << "Escaped in " << ans << " minute(s)." << endl;
	}
	return 0;
}

int bfs(){
	Node node(a1, a2, a3, 0);
	queue<Node> q;
	while (!q.empty())   q.pop();
	q.push(node);
	while (!q.empty()){
		node = q.front();
		q.pop();
		if (node.x == b1&&node.y == b2&&node.z == b3)	return node.step;
		vis[node.x][node.y][node.z] = true;
		for (int i = 0; i < 6; i++){
			int x = node.x + strpArr[i][0];
			int y = node.y + strpArr[i][1];
			int z = node.z + strpArr[i][2];
			if (x >= 0 && x < m&&y >= 0 && y < n&&z >= 0 && z < k&&!vis[x][y][z] && (trap[x][y][z] == '.'||trap[x][y][z]=='E')){
				vis[x][y][z] = true;
				Node next(x, y, z, node.step + 1);
				q.push(next);
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值