zoukankan      html  css  js  c++  java
  • 深度优先算法DFS

    英雄要从H点出发,去解救位于M点的美女。

    迷宫的围墙用#表示,带*号的位置表示有杀手埋伏,这些点都是不能走的,

    那么英雄要最少走多少步才能解救美女呢?

    package myalgorithm;
    import java.util.Arrays;
    import java.util.LinkedList;
    import java.util.Queue;
    public class ShortPath {
        /*全局最短路径*/
        public int stepnum = 999;
        /*构建11*11的迷宫,英雄H在(1,1)的位置出发,去解救美女M(6,8)*/
        char[][] graph = {
                {'#','#','#','#','#','#','#','#','#','#','#'},
                {'#','H','_','_','*','_','_','*','_','_','#'},
                {'#','_','_','_','_','_','_','_','_','_','#'},
                {'#','_','*','_','_','_','*','_','_','_','#'},
                {'#','_','_','_','*','_','_','_','_','*','#'},
                {'#','_','_','_','_','_','_','*','_','*','#'},
                {'#','_','*','_','_','_','_','_','M','_','#'},
                {'#','*','_','_','*','_','_','_','_','_','#'},
                {'#','_','_','_','_','_','_','_','_','_','#'},
                {'#','_','_','_','*','_','_','_','_','_','#'},
                {'#','#','#','#','#','#','#','#','#','#','#'},
        };
        /*初始标记数组都为0*/
        public int[][] mark = new int[graph.length][graph.length];
        /*每一个位置有四种选择:右下左上*/
        public int[][] choose = {
                {0,1},
                {1,0},
                {0,-1},
                {-1,0}
        };
        /*采用递归的DFS算法*/
        public void DFS(int x,int y, int step) {
            /*找到美女M*/
            if (graph[x][y] == 'M')
            {
                if(step < stepnum)
                {
                    stepnum = step;
                }
                return;//找到之后立即返回,不再继续
            }
    
            //新位置
            int tx = 0;
            int ty = 0;
            for(int i=0;i<4;i++)
            {
                tx = x + choose[i][0];
                ty = y + choose[i][1];
                if(graph[tx][ty] != '#' 
                        && graph[tx][ty] != '*' 
                        && mark[tx][ty] == 0)
                {
                    mark[tx][ty] = 1;//标记该点已经走过
                    DFS(tx,ty,step+1);
                    mark[tx][ty] = 0;//取消该点的标记
                }
            }
            return;
        }
       public static void main(String[] args) {
            ShortPath my = new ShortPath();long start1 = System.currentTimeMillis();
            my.mark[1][1] = 1;
            my.DFS(1,1,0);long end1 = System.currentTimeMillis();
            System.out.println("DFS step: " + my.stepnum + " time:" + (end1-start1));
        }
    
    }

    非常耗时:DFS step: 12 time:109830

  • 相关阅读:
    损失函数及经验风险和结构风险
    ML面试题网站及ML模型网站
    数据归一化
    逻辑回归
    什么是凸函数及如何判断一个函数是否是凸函数
    Feature Selection Can Reduce Overfitting And RF Show Feature Importance
    Python Machine Learning-Chapter4
    skywalking与pinpoint全链路追踪方案对比
    全)Java从单体到微服务打造房产销售平台 2018年慕课网 高清视频+源码
    CentOS7 通过YUM安装MySQL5.7
  • 原文地址:https://www.cnblogs.com/mingziday/p/4822761.html
Copyright © 2011-2022 走看看