1096. 地牢大师 Java题解 (bfs)

32 篇文章 1 订阅
30 篇文章 1 订阅

输入样例:

3 4 5
S....
.###.
.##..
###.#

#####
#####
##.##
##...

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

输出样例:

Escaped in 11 minute(s).
Trapped!

解题思路:

献给阿尔吉侬的花束的三维扩展,只需要在偏移量上多加两个判断方向,再把二维数组换成三维数组即可。

Java代码:

import java.io.*;
import java.util.*;

public class Main {
	static int l, r, c;
	static int [][][]map;
	static boolean [][][]vis;
	static Point start;
	static Point end;
	static int []dz = {-1, 1, 0, 0, 0, 0};//偏移量 
	static int []dx = {0, 0, -1, 0, 1, 0};
	static int []dy = {0, 0, 0, 1, 0, -1};
	
	static class Point{
		int z, x, y;
		int step;
		public Point(int z, int x, int y, int step) {
			this.z = z;
			this.x = x;
			this.y = y;
			this.step = step;
		}
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while(true) {
			String str = br.readLine();
			if(str.equals("0 0 0")) break;
			String[] split = str.split(" ");
			l = Integer.parseInt(split[0]);
			r = Integer.parseInt(split[1]);
			c = Integer.parseInt(split[2]);
			
			map = new int[l][r][c];
			vis = new boolean[l][r][c];
			for(int i = 0; i < l; i++) {
				for(int j = 0; j < r; j++) {
					String s = br.readLine();
					for(int k = 0; k < c; k++) {
						map[i][j][k] = s.charAt(k);
						if(map[i][j][k] == 'S') start = new Point(i, j, k, 0);
						if(map[i][j][k] == 'E') end = new Point(i, j, k, 0);
						if(map[i][j][k] != '#') vis[i][j][k] = true;
					}
				}
				br.readLine();
			}
			bfs();
		}
	}
	
	public static void bfs() {
		Queue<Point> qu = new LinkedList<>();
		qu.add(start);
		while(!qu.isEmpty()) {
			Point p = qu.poll();
			vis[p.z][p.x][p.y] = false;
			if(p.z == end.z && p.x == end.x && p.y == end.y) {
				System.out.printf("Escaped in %d minute(s).\n", p.step);
				return;
			}
			for(int i = 0; i < 6; i++) {
				int z = p.z + dz[i], x = p.x + dx[i], y = p.y + dy[i];
				if(z < 0 || z >= l || x < 0 || x >= r || y < 0 || y >= c) continue;
				if(map[z][x][y] != '#' && vis[z][x][y]) {
					qu.add(new Point(z, x, y, p.step + 1));
					vis[z][x][y] = false;
				}
			}
		}
		System.out.println("Trapped!");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值