简单深度优先搜索

深度优先遍历过程。
从一个点向下试,直到试不下去为止。
图与树不同,树从一个根开始,向下走,一定有走不下去的时候,而图存在环,为此,需要记录每一个点是否被遍历过了,如果被遍历过,在下面的遍历中就不需要走了,当没有相邻节点时,就退回。

假设迷宫有5行4列
二维数组0表示空地 1表示障碍物,入口为0,0
步数最少到达3,2

//深度优先搜索迷宫问题
public class Dfs {
      int p;
      int q;
      int min =Integer.MAX_VALUE;
      int m;
      int n;
      int book[][] = new int [50][50];
      int next[][] ={{0,1},{1,0},{0,-1},{-1,0}};
      int a[][];


    /**
     * @return the min
     */
    public int getMin() {
        return min;
    }

    /**
     * @param min the min to set
     */
    public void setMin(int min) {
        this.min = min;
    }

    /**
     * @return the p
     */
    public int getP() {
        return p;
    }

    /**
     * @param p the p to set
     */
    public void setP(int p) {
        this.p = p;
    }

    /**
     * @return the q
     */
    public int getQ() {
        return q;
    }

    /**
     * @param q the q to set
     */
    public void setQ(int q) {
        this.q = q;
    }

    /**
     * @return the m
     */
    public int getM() {
        return m;
    }

    /**
     * @param m the m to set
     */
    public void setM(int m) {
        this.m = m;
    }

    /**
     * @return the n
     */
    public int getN() {
        return n;
    }

    /**
     * @param n the n to set
     */
    public void setN(int n) {
        this.n = n;
    }

    /**
     * @return the a
     */
    public int[][] getA() {
        return a;
    }

    /**
     * @param a the a to set
     */
    public void setA(int[][] a) {
        this.a = a;
    }

    public void dfs(int x,int y,int step){
        int tx;
        int ty;
        int k;
        if(x==p-1&&y==q-1){
          if(step<min){
            min = step;
            setMin(min);
          }
            return ;
        }

        for( k=0;k<4;k++){
            tx=x+next[k][0];
            ty=y+next[k][1];
            if(tx>=m||ty>=n||tx<0||ty<0)
            {
                continue;
            }
            if(book[x][y]==0&&a[x][y]==0){
                book[x][y] =1;
                dfs(tx,ty,step+1);
                book[x][y] =0;
            }



        }
        return;

    }

    public static void main(String[] args) {
        Dfs dfs = new Dfs();
        int a[][]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}};
        dfs.setA(a);
        dfs.setM(5);
        dfs.setN(4);
        dfs.setP(4);
        dfs.setQ(3);
        dfs.dfs(0, 0, 0);
        System.out.println(dfs.getMin());


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值