Maze of data structures and algorithms

Maze of data structures and algorithms


table of Contents

  1. Maze
  2. Code
  3. Discussion of the maze of

1. Maze

Here Insert Picture Description
See Detailed specific code comments


2. code implementation

public class MiGong {
    public static void main(String[] args) {
        //先创建一个二维数组模拟迷宫
        //地图
        int[][] map = new int[8][7];
        //使用1表示墙
        //上下全部置为1
        for (int i = 0; i < 7; i++) {
            map[0][i] = 1;
            map[7][i] = 1;
        }
        //左右全部置为1
        for (int i = 0; i < 8; i++) {
            map[i][0] = 1;
            map[i][6] = 1;
        }

        //设置挡板
        map[3][1] = 1;
        map[3][2] = 1;

        //输出地图
        System.out.println("输出地图的情况");
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j] + "\t");
            }
            System.out.println();
        }

        //使用递归回溯给小球找路
        setWay(map,1,1);

        //输出新的地图,小球走过,并标识过的地图
        System.out.println("小球走过,并标识过的地图");
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j] + "\t");
            }
            System.out.println();
        }
    }

    //使用递归回溯来给小球找路

    /**
     * 说明
     * 1. i,j表示从地图哪个位置开始出发
     * 2. 如果小球能到map[6][5]
     * 3. 约定: 当map[i][j] 为0表示该点没有走过,当1为墙,2表示通路可以走,3表示该点走过,但走不通
     * 4. 在走迷宫时需要确定一个策略(方法),下->右->上->左 ,如果走不通再回溯
     *
     * @param map 表示地图
     * @param i   i   从哪个位置开始找
     * @param j
     * @return 如果找到通路,就返回true,否则false
     */
    public static boolean setWay(int[][] map, int i, int j) {
        if (map[6][5] == 2) {     //说明通路找到

            return true;
        } else {
            if (map[i][j] == 0) { //如果当前这个点没有走过
                //按照策略 下->右->上->左
                map[i][j] = 2; //假定该点是可以走通。
                if (setWay(map, i + 1, j)) { //向下走
                    return true;
                } else if (setWay(map, i, j + 1)) { //向右走
                    return true;
                } else if (setWay(map, i - 1, j)) { //向上走
                    return true;
                } else if (setWay(map, i, j - 1)) { //向左走
                    return true;
                }else {
                    //说明该点是走不通的,死路
                    map[i][j] = 3;
                    return false;
                }
            }else {  //如果map[i][j] !=0,可能是1,2,3
                return false;
            }
        }
    }
}

Compile the results:
Here Insert Picture Description

3. Discussion of the maze of

  1. The path to get the ball, and programmers set about to find a way strategy namely: order to find a way around the upper and lower correlation

Guess you like

Origin blog.csdn.net/weixin_41910694/article/details/92843697