java迷宫回溯找最短路径问题(多策略)

1、首先我们先明确迷宫,并创建

如上图,1为墙,中间的1为挡板墙,

由图我们可以看出这是一个二维数组

/**
     * 创建地图
     * @return
     */
    public static int [][] createMap(){
        int [][] mapNew = new int[8][7];
        //1表示墙,不能走
        for (int i=0;i<7;i++){
            mapNew[0][i] = 1;
            mapNew[7][i] = 1;
        }
        //1表示墙,不能走
        for (int i=0;i<8;i++){
            mapNew[i][0] = 1;
            mapNew[i][6] = 1;
        }
        //设置墙体
        setWall(mapNew,1,4);
        setWall(mapNew,2,4);
        setWall(mapNew,3,1);
        setWall(mapNew,3,2);
        setWall(mapNew,5,3);
        setWall(mapNew,5,4);
        setWall(mapNew,6,4);
        return mapNew;
    }
    /**
     *设置挡板
     */
    public static void setWall(int [][] mapNew, int i, int j){
        mapNew[i][j] = 1;
    }
    /**
     * 展示地图
     * @param map
     */
    public static void showMap(int [][] map){
        for (int i = 0; i < map.length; i++) {
            int [] item = map[i];
            for (int j = 0; j < item.length; j++) {
                System.out.print(item[j]+" ");
            }
            System.out.println();
        }
    }

2、开始寻找路线

思路:

1:设定map[1][1]为起始位置,map[6][5]为出口位置

2:0表示还未走过可以走,如果走过则标记为2

3:定义小球的行走策略,小球按着上-右-下-左的顺序走(走的策略可以自己定义,策略会决定路 线)

4:小球走过的路线不允许走

5:如果是死路,则标记为3

开始编码:

 /**
     * 寻找路线
     * @param i
     * @param j
     * @return
     */
    public static boolean getWay(int i, int j){

        //如果出口为2,则说明找到了出口
        if(map[6][5] == 2){
            return true;
        }else{
            //如果是0则可以走,并标记为2
            if(map[i][j] == 0){
                map[i][j] = 2;
                //接下来小球就按定义的策略执行
                //按四个方向开始探测(上-右-下-左)
                if(getWay(i-1,j)){//如果上行可以走
                    return true;
                }else if(getWay(i,j+1)){ //右
                    return true;
                }else if(getWay(i+1,j)){ //下
                    return true;
                }else if(getWay(i,j-1)){//左
                    return true;
                }else{
                    //这种情况就是小球上下左右都行不通了
                    map[i][j] = 3;
                    return false;
                }
            }
            return false;
        }
    }

注意,这里有个递归回溯,大家可以了解一下递归的运行机制,涉及到的知识点。

回溯到上一步后,继续尝试向右运行,推到栈中,发现是0不是墙,则继续先向上探索,发现是墙,在回溯,一直重复此过程,知道找到map[6][5] == 0并标记为2,则退出递归,从而找到出口

完整代码

public class 迷宫回溯单测略 {

    public static int [][] map;

    public static void main(String[] args) {
        //创建地图
        map = createMap();

        //寻找路线
        getWay(1,1);
        showMap(map);
    }

    /**
     * 创建地图
     * @return
     */
    public static int [][] createMap(){
        int [][] mapNew = new int[8][7];
        //1表示墙,不能走
        for (int i=0;i<7;i++){
            mapNew[0][i] = 1;
            mapNew[7][i] = 1;
        }
        //1表示墙,不能走
        for (int i=0;i<8;i++){
            mapNew[i][0] = 1;
            mapNew[i][6] = 1;
        }
        //设置墙体
        setWall(mapNew,1,4);
        setWall(mapNew,2,4);
        setWall(mapNew,3,1);
        setWall(mapNew,3,2);
        setWall(mapNew,5,3);
        setWall(mapNew,5,4);
        setWall(mapNew,6,4);
        return mapNew;
    }

    public static void setWall(int [][] mapNew, int i, int j){
        mapNew[i][j] = 1;
    }
    /**
     * 展示地图
     * @param map
     */
    public static void showMap(int [][] map){
        for (int i = 0; i < map.length; i++) {
            int [] item = map[i];
            for (int j = 0; j < item.length; j++) {
                System.out.print(item[j]+" ");
            }
            System.out.println();
        }
    }

    /**
     * 寻找路线
     * @param i
     * @param j
     * @return
     */
    public static boolean getWay(int i, int j){

        //如果出口为2,则说明找到了出口
        if(map[6][5] == 2){
            return true;
        }else{
            //如果是0则可以走,并标记为2
            if(map[i][j] == 0){
                map[i][j] = 2;
                //接下来小球就按定义的策略执行
                //按四个方向开始探测(上-右-下-左)
                if(getWay(i-1,j)){//如果上行可以走
                    return true;
                }else if(getWay(i,j+1)){ //右
                    return true;
                }else if(getWay(i+1,j)){ //下
                    return true;
                }else if(getWay(i,j-1)){//左
                    return true;
                }else{
                    //这种情况就是小球上下左右都行不通了
                    map[i][j] = 3;
                    return false;
                }
            }
            return false;
        }
    }


}

多策略模式

上面我们是规定死了小球走的策略即上-右-下-左,并且,从步数来看,这肯定不是小球找到出路的最佳步数,从图中我们看到小球甚至走了两个死步,就是3

经过我们分析,小球先向下走,在向右走,走的步数是最少的,但这只是我们的猜测,接下来验证我们的猜测对不对。

  1. 生成策略

上下左右四个方向,排列组合,用递归方式生成策略

A44 = 4*3*2*1 = 24种

最后统一上代码,这里只展示这个方法

direction和clArr均为静态属性,后续有全部代码

/**
     * 获取所有策略
     */
    public static void getAllCl(String[] resultList, int resultIndex){
        direction[0] = "top";
        direction[1] = "right";
        direction[2] = "bottom";
        direction[3] = "left";
        int length = resultList.length;
        if(resultIndex>= length){
//            System.out.println("处理完成");
            //深拷贝resultList到策略数组中
            clArr.add( Arrays.copyOf(resultList,resultList.length));
            return;
        }
        for (int i=0;i<direction.length;i++){
            boolean exists = false;
            for (int j=0;j<resultIndex;j++){
                if (direction[i].equals(resultList[j])) {
                    exists = true;
                    break;
                }
            }
            if (!exists) { // 排列结果不存在该项,才可选择
                resultList[resultIndex] = direction[i];
                getAllCl(resultList, resultIndex + 1);
            }
        }

    }

这里展示递归思路图,因为4个元素的递归深度很深,所以我用三个元素来演示

  1. 有了策略之后,我们生成地图

注意:这里可以用一张地图,也可以每个策略对应一张,我建议选后者,因为思路清晰,能看到每个策略走完的轨迹

我们通过一个对象来记录策略和步数和地图

我们生成完策略之后,遍历来创建一个一个的对象

 public static void main(String[] args) {
        //创建地图
//        int [][] map = new int[8][7];

        //生成策略
        getAllCl(new String[4],0);

//        [left, bottom, right, top]

        String []clMock = new String[4];
        clMock[0] = "top";
        clMock[1] = "right";
        clMock[2] = "bottom";
        clMock[3] = "left";

        for (int i=0;i<clArr.size();i++){
            //开始寻找路线
            String [] clItem = clArr.get(i);
            //创建地图
            int [][] newMap = createMap();
            showMap(newMap);
            System.out.println(" ");
            //创建对象
            MapObj mapObj = new MapObj(newMap,0,clItem);
        }
    }

创建完之后,开始针对不同的策略来找路径

思路跟单策略找是一样的

/**
     * 思路:
     * 1:设定map[6][5]为出口
     * 2:0表示还未走过,如果小球走过则标记为2
     * 3:小球按着上-右-下-左的顺序走(走的策略自己定义,策略会决定路线)
     * 4:如果小球走过的路径则不允许走
     * 5:如果是死路则标记为3
     * @param i 点i坐标
     * @param j 点的j坐标
     * @return
     */
    public static boolean setWay(MapObj mapObj, int i,int j){
        String [] cl = mapObj.getCl();
        int [][] map = mapObj.getMap();
//        map[6][5]为出口,找到出口退出递归
        mapObj.setStep(mapObj.getStep()+1);
        if(map[6][5] == 2){
            resultList.add(mapObj);
            return true;
        }else{
            //如果当前位置可以走则返回true,并将该位置标记为已走过
            if(map[i][j] == 0){
                map[i][j] = 2;

                boolean flag = false;
                //策略不固定所以循环来判断往哪个方向走
                for (int k = 0; k < cl.length; k++) {
                    String item = cl[k];
                    if(item.equals("top") && setWay(mapObj,i-1,j)){//上行
                        return true;
                    }else if(item.equals("right") && setWay(mapObj,i,j+1)){ //右行
                        return true;
                    }else if(item.equals("bottom") && setWay(mapObj,i+1,j)){ //下行
                        return true;
                    }else if(item.equals("left") && setWay(mapObj,i,j-1)){ //左行
                        return true;
                    }
                }
                //如果四个方向都走不通则是死路,标记为3
                map[i][j] = 3;
                flag = false;
                return flag;
                //但策略思路
//                if(setWay(mapObj,i-1,j)){//上行
//                    return true;
//                }else if(setWay(mapObj,i,j+1)){ //右行
//                    return true;
//                }else if(setWay(mapObj,i+1,j)){ //下行
//                    return true;
//                }else if(setWay(mapObj,i,j-1)){ //左行
//                    return true;
//                }else{
//                    map[i][j] = 3;
//                    return false;
//                }
            }else{
                return false;
            }
        }
    }

OK 这样我们就算是完成了

最后的结果为

接下来贴上多策略完整代码,如果大家想看所有的结果,resultList这个就是,遍历打印即可

import java.util.*;

public class 迷宫回溯 {

    public static String [] direction = new String[4];

    public static List<String []> clArr = new ArrayList();

    //用来储存结果
    public static List<MapObj> resultList = new ArrayList();

    //用来记录步数
    public static int step;

    public static void main(String[] args) {
        //创建地图
//        int [][] map = new int[8][7];

        //生成策略
        getAllCl(new String[4],0);

//        [left, bottom, right, top]

        String []clMock = new String[4];
        clMock[0] = "top";
        clMock[1] = "right";
        clMock[2] = "bottom";
        clMock[3] = "left";

        for (int i=0;i<clArr.size();i++){
            //开始寻找路线
            String [] clItem = clArr.get(i);
            //创建地图
            int [][] newMap = createMap();
            showMap(newMap);
            System.out.println(" ");
            //创建对象
            MapObj mapObj = new MapObj(newMap,0,clItem);
            setWay(mapObj,1,1);
        }
        System.out.println("查询完路线以后");
        //将结果排序
//        resultList.sort(new Comparator<MapObj>() {
//            @Override
//            public int compare(MapObj a, MapObj b) {
//                return a.getStep()-b.getStep();
//            }
//        });
        //将结果排序优化
//        resultList.sort((MapObj a,MapObj b)-> a.getStep()-b.getStep());
        //将结果排序再优化
        resultList.sort(Comparator.comparingInt(MapObj::getStep));

        System.out.printf("最短的步数为:%d \n",resultList.get(0).getStep());
        System.out.printf("最短的策略为:%s \n",Arrays.toString(resultList.get(0).getCl()));
        System.out.println("地图路线为:");
        showMap(resultList.get(0).getMap());


    }

    /**
     * 创建地图
     * @return
     */
    public static int [][] createMap(){
        int [][] mapNew = new int[8][7];
        //1表示墙,不能走
        for (int i=0;i<7;i++){
            mapNew[0][i] = 1;
            mapNew[7][i] = 1;
        }
        //1表示墙,不能走
        for (int i=0;i<8;i++){
            mapNew[i][0] = 1;
            mapNew[i][6] = 1;
        }
        //设置墙体
        setWall(mapNew,1,4);
        setWall(mapNew,2,4);
        setWall(mapNew,3,1);
        setWall(mapNew,3,2);
        setWall(mapNew,5,3);
        setWall(mapNew,5,4);
        setWall(mapNew,6,4);
        return mapNew;
    }

    /**
     * 设置挡板
     * @param mapNew
     * @param i
     * @param j
     */
    public static void setWall(int [][] mapNew, int i, int j){
        mapNew[i][j] = 1;
    }

    /**
     * 思路:
     * 1:设定map[6][5]为出口
     * 2:0表示还未走过,如果小球走过则标记为2
     * 3:小球按着上-右-下-左的顺序走(走的策略自己定义,策略会决定路线)
     * 4:如果小球走过的路径则不允许走
     * 5:如果是死路则标记为3
     * @param i 点i坐标
     * @param j 点的j坐标
     * @return
     */
    public static boolean setWay(MapObj mapObj, int i,int j){
        String [] cl = mapObj.getCl();
        int [][] map = mapObj.getMap();
//        map[6][5]为出口,找到出口退出递归
        mapObj.setStep(mapObj.getStep()+1);
        if(map[6][5] == 2){
            resultList.add(mapObj);
            return true;
        }else{
            //如果当前位置可以走则返回true,并将该位置标记为已走过
            if(map[i][j] == 0){
                map[i][j] = 2;

                boolean flag = false;
                //策略不固定所以循环来判断往哪个方向走
                for (int k = 0; k < cl.length; k++) {
                    String item = cl[k];
                    if(item.equals("top") && setWay(mapObj,i-1,j)){//上行
                        return true;
                    }else if(item.equals("right") && setWay(mapObj,i,j+1)){ //右行
                        return true;
                    }else if(item.equals("bottom") && setWay(mapObj,i+1,j)){ //下行
                        return true;
                    }else if(item.equals("left") && setWay(mapObj,i,j-1)){ //左行
                        return true;
                    }
                }
                //如果四个方向都走不通则是死路,标记为3
                map[i][j] = 3;
                flag = false;
                return flag;
                //但策略思路
//                if(setWay(mapObj,i-1,j)){//上行
//                    return true;
//                }else if(setWay(mapObj,i,j+1)){ //右行
//                    return true;
//                }else if(setWay(mapObj,i+1,j)){ //下行
//                    return true;
//                }else if(setWay(mapObj,i,j-1)){ //左行
//                    return true;
//                }else{
//                    map[i][j] = 3;
//                    return false;
//                }
            }else{
                return false;
            }
        }
    }

    /**
     * 获取所有策略
     */
    public static void getAllCl(String[] resultList, int resultIndex){
        direction[0] = "top";
        direction[1] = "right";
        direction[2] = "bottom";
        direction[3] = "left";
        int length = resultList.length;
        if(resultIndex>= length){
//            System.out.println("处理完成");
            //深拷贝resultList到策略数组中
            clArr.add( Arrays.copyOf(resultList,resultList.length));
            return;
        }
        for (int i=0;i<direction.length;i++){
            boolean exists = false;
            for (int j=0;j<resultIndex;j++){
                if (direction[i].equals(resultList[j])) {
                    exists = true;
                    break;
                }
            }
            if (!exists) { // 排列结果不存在该项,才可选择
                resultList[resultIndex] = direction[i];
                getAllCl(resultList, resultIndex + 1);
            }
        }

    }

    /**
     * 展示地图
     * @param map
     */
    public static void showMap(int [][] map){
        for (int i = 0; i < map.length; i++) {
            int [] item = map[i];
            for (int j = 0; j < item.length; j++) {
                System.out.print(item[j]+" ");
            }
            System.out.println();
        }
    }
}

class MapObj{
    private int [][] map;
    private int step;
    private String [] cl;

    public MapObj(int[][] map, int step, String[] cl) {
        this.map = map;
        this.step = step;
        this.cl = cl;
    }


    public int[][] getMap() {
        return map;
    }

    public void setMap(int[][] map) {
        this.map = map;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }

    public String[] getCl() {
        return cl;
    }

    public void setCl(String[] cl) {
        this.cl = cl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城狮狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值