数据结构与算法之-递归(迷宫与8皇后问题)

1.背景

2.迷宫问题

package com.ldp.structure.demo01;

import org.junit.Test;

/**
 * @create 04/12 6:38
 * @description <p>
 * 递归生成迷宫
 * </p>
 */
public class Test07Recursion {
    int rowMax = 5;
    int colMax = 5;
    int rowInt = 1;
    int colInt = 1;
    int rowEnd = 4;
    int colEnd = 1;

    @Test
    public void test01() {
        int[][] array = init();
        print(array, "初始化");
        go(array, rowInt, colInt, "初始位置");
        print(array, "结果");
    }

    /**
     * 寻找路
     * 1. 0表示可以走的路,1表示墙,2表示走过的路,3表示走不通的路
     * 2. 起点(1,1)到达终点(7,7)
     * 3.走的逐步尝试(下->右->上->左)
     */
    public boolean go(int[][] array, int row, int col, String message) {
        // print(array, message);
        if (array[rowEnd][colEnd] == 2) {
            // 表示以到终点
            return true;
        } else if (array[row][col] == 0) {
            // 可以走的路
            // 假定能走通
            array[row][col] = 2;
            if (go(array, row + 1, col, "下")) {// 向下走
                return true;
            } else if (go(array, row, col + 1, "右")) {// 向右走
                return true;
            } else if (go(array, row - 1, col, "上")) {// 向上走
                return true;
            } else if (go(array, row, col - 1, "左")) {// 向左走
                return true;
            } else {
                // 走不通是死路
                array[row][col] = 3;
                return false;
            }
        } else {
            // array[row][col]==1 || array[row][col]==3  走不通返回false
            return false;
        }
    }

    /**
     * 初始化一个8*8的迷宫
     * 1. 0表示可以走的路,1表示墙,2表示走过的路,3表示走不通的路
     * 2. 起点(1,1)到达终点(7,7)
     *
     * @return
     */
    public int[][] init() {
        int[][] array = new int[rowMax + 1][colMax + 1];
        // 第一行与最后一行是墙
        for (int i = 0; i <= colMax; i++) {
            array[0][i] = 1;
            array[rowMax][i] = 1;
        }
        // 第一列与最后一列是墙
        for (int i = 0; i <= rowMax; i++) {
            array[i][0] = 1;
            array[i][colMax] = 1;
        }
        // 定义左侧支部墙
        array[3][1] = 1;
        array[3][2] = 1;
        //  array[3][3] = 1;
        return array;
    }

    public void print(int[][] array, String message) {
        System.out.println("--------------迷宫图形----------------" + message);
        for (int i = 0; i <= rowMax; i++) {
            for (int j = 0; j <= colMax; j++) {
                // System.out.printf("\t %d(%d,%d)", array[i][j], i, j);
                System.out.printf("\t %d", array[i][j]);
            }
            System.out.println();
            // System.out.println();
        }
    }
}

 3.8皇后问题

 

完美!

posted @ 2022-04-12 08:29  不停学  阅读(43)  评论(0)    收藏  举报