HDOJ2102 A计划

来源:互联网 发布:sql select 结果拼接 编辑:程序博客网 时间:2024/06/08 17:04


本题涉及搜索,可用DFS(深搜)解决

博主有一篇关于 深搜原理 的博客,不知道原理的可以去看看,懂深搜看下面代码(java):

import java.util.Scanner; class Main{    public static void main(String[] args) {        Scanner sc=new Scanner(System.in);        while(sc.hasNext()){            int C=sc.nextInt();            while(C-->0){                int n=sc.nextInt();                int m=sc.nextInt();                int t=sc.nextInt();                time=-1;                Plot[][][] plots=new Plot[2][n][m];                Plot p = null;                for (int i = 0; i < plots.length; i++) {                    for (int j = 0; j < plots[i].length; j++) {                        String str=sc.next();                        for (int k = 0; k < plots[i][j].length; k++) {                            char c=str.charAt(k);                            plots[i][j][k]=new Plot(i,j,k,c);                            if(c=='P')                                p=plots[i][j][k];                        }                    }                }                searchDFS(plots,plots[0][0][0]);                if(p.time!=0&&p.time<=t)                    System.out.println("YES");                else                    System.out.println("NO");            }        }    }    static int[][] dir={        {0,-1},                         {-1,0},        {1,0},                                 {0,1}      };    static int time=-1;    private static void searchDFS(Plot[][][] plots,Plot u) {        time++;//进来+1秒        u.isVisit=true;//涂黑        if (u.time==0||u.time > time)             u.time = time;//记录第一次时间及最短访问时间        if(u.c=='P')//找到,此次访问结束            return;        for (int i = 0; i < dir.length; i++) {//对前后左右访问            int x=u.x;            int y=u.y+dir[i][0];            int z=u.z+dir[i][1];            //可访问,递归            if(y>=0&&y<plots[x].length && z>=0&&z<plots[x][y].length                    && (plots[x][y][z].c=='.'||plots[x][y][z].c=='P' )&& !plots[x][y][z].isVisit){                searchDFS(plots, plots[x][y][z]);                //还原                plots[x][y][z].isVisit=false;                time--;            }else if(y>=0&&y<plots[x].length && z>=0&&z<plots[x][y].length                    && plots[x][y][z].c=='#' && !plots[x][y][z].isVisit){                //穿越层次                x=(1-x);                //可穿,递归                if((plots[x][y][z].c=='.'||plots[x][y][z].c=='P' )&& !plots[x][y][z].isVisit){                    searchDFS(plots, plots[x][y][z]);                    plots[x][y][z].isVisit=false;                    time--;                }            }        }    }}class Plot{    int x,y,z;    int time;    char c;    boolean isVisit;    public Plot(int x,int y,int z,char c) {        this.x = x;        this.y = y;        this.z = z;        this.c = c;    }    Plot parent;}


0 0