专题(六)双指针、BFS与图论——AcWing 1113. 红与黑 AcWing 1096. 地牢大师
发布日期:2021-05-08 21:31:10 浏览次数:13 分类:精选文章

本文共 2367 字,大约阅读时间需要 7 分钟。

【题目描述】

【思路】

还是BFS 只不过由二维变到三维而已
要注意三维数组 三个维度 分别表示行、列、高度

import java.io.*;import java.util.Queue;import java.util.LinkedList;class Node{       int x, y, z, step;    public Node(int xx, int yy, int zz,int tt){           x = xx;        y = yy;        z = zz;        step = tt;    }}class Main{       static int N = 110;    static char[][][]g = new char[N][N][N];//三维 x、y、z    //上下 顺时针自北(x轴正方向)    static int dx[] = {   0, 0, 1, 0, -1, 0};    static int dy[] = {   0, 0, 0, -1, 0, 1};    static int dz[] = {   1, -1, 0, 0, 0, 0};        public static String bfs(int sx, int sy, int sz, int R, int C, int T){           Queue
q = new LinkedList
(); q.offer(new Node(sx, sy, sz,0)); g[sx][sy][sz] = '#'; while(!q.isEmpty()){ Node h = q.poll(); int x = h.x, y = h.y, z = h.z, step = h.step; for(int i = 0; i < 6; i++){ int a = x + dx[i], b = y + dy[i], c = z +dz[i]; if( a < 0 || a >= R || b < 0 || b >= C || c < 0 || c >= T ) continue; if( g[a][b][c] == '#' ) continue; if(g[a][b][c] == 'E') return "Escaped in "+(step + 1)+ " minute(s)."; q.offer(new Node(a, b, c, step + 1)); g[a][b][c] = '#'; } } return "Trapped!"; } public static void main(String args[]) throws Exception{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); while(true){ String s[] = bf.readLine().split(" "); int T = Integer.parseInt(s[0]), R = Integer.parseInt(s[1]), C = Integer.parseInt(s[2]); if( T == 0 && R == 0 && C == 0) break; int sx = 0, sy = 0, sz = T; for(int i = 0; i < T; i ++){ //每次读取一层 //每一层为一个R行K列的数组数组 for(int j = 0; j < R; j ++){ String str = bf.readLine(); for(int k = 0; k < C; k ++){ g[j][k][i] = str.charAt(k); if(g[j][k][i] == 'S'){ sx = j; sy = k; sz =i; } } } //读取空行 bf.readLine(); } System.out.println(bfs(sx, sy, sz, R, C, T)); } }}
上一篇:专题(六)双指针、BFS与图论——AcWing 1233. 全球变暖
下一篇:剑指Offer打卡day12——AcWing 32. 调整数组顺序使奇数位于偶数前面

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月20日 14时48分24秒