poj2251

来源:互联网 发布:通过网络社会治理案例 编辑:程序博客网 时间:2024/05/01 19:48
涉及算法:广度搜索(bfs)
题目大意:现有一个三维的牢房,该牢房有a层,每一层有b排c列房间,现给定一个起始房间和一个终点房间,问是否可以从起点房间到达终点房间,如果可以,最少需要多少时间?
注意:每一分钟移动一步,可以往上下左右前后6个方向移动
题目分析:用一个三维数组表示地牢,值为1表示不能通行,为0表示可以通行,bfs直接搜索终点
代码如下:
package com.solo.bfs;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.LinkedList;import java.util.Queue;public class Main_2251 {static int END=2;static int a,b,c;//地牢的层、行、列static int[][][] maze;//maze[i][j][k]=0:地牢的第i层j行k列的房间是空的可以通行,=1表示不可以通行static int startX,startY,startZ;//起始位置static int mStep;static int[][] d={{-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1}};static int[][][] vis;static Queue<P> q;static P head;public static void main(String[] args) throws IOException {BufferedReader in=new BufferedReader(new InputStreamReader(System.in));String s;String[] str=new String[3];while(!(s=in.readLine()).equals("0 0 0")){mStep=100000;q=new LinkedList<P>();str=s.split(" ");a=Integer.valueOf(str[0]);b=Integer.valueOf(str[1]);c=Integer.valueOf(str[2]);maze=new int[a][b][c];vis=new int[a][b][c];for(int i=0;i<a;i++){for(int j=0;j<b;j++){s=in.readLine();for(int k=0;k<c;k++){if(s.charAt(k)=='#') maze[i][j][k]=1;else if (s.charAt(k)=='.') maze[i][j][k]=0;else if(s.charAt(k)=='S'){maze[i][j][k]=0;startX=i;startY=j;startZ=k;}else if(s.charAt(k)=='E'){maze[i][j][k]=END;}}}s=in.readLine();}bfs();if(mStep==100000){System.out.println("Trapped!");}else {System.out.println("Escaped in "+mStep+" minute(s).");}}}static class P//地牢房间的位置信息和走到该房间需要的时间{int x,y,z,step;P(int x,int y,int z,int step){this.x=x;this.y=y;this.z=z;this.step=step;}}static void bfs(){int cx=0,cy=0,cz=0;int x=0,y=0,z=0;q.offer(new P(startX,startY,startZ,1));vis[startX][startY][startX]=1;while(!q.isEmpty()){head=q.poll();x=head.x;y=head.y;z=head.z;for(int i=0;i<6;i++){cx=x+d[i][0];cy=y+d[i][1];cz=z+d[i][2];if(cx>=0 && cx<a && cy>=0 && cy<b && cz>=0 && cz<c){if(vis[cx][cy][cz]==0 && maze[cx][cy][cz]!=1){q.offer(new P(cx,cy,cz,head.step+1));vis[cx][cy][cz]=1;if(maze[cx][cy][cz]==END){mStep=head.step;return;}}}}}}}





0 0
原创粉丝点击