数据结构与算法 08 递归 迷宫问题 八皇后问题

递归 recursion

递归调用规则:

  1. 当程序执行到一个方法时,就会开辟一个独立的空间(栈)
  2. 每个空间的数据(局部变量)是独立的
  3. 调用自身方法,向上继续开辟空间
  4. 自顶向下进行执行
package recursion;

public class Demo00 {
    public static void main(String[] args) {
        test(4);
    }
    public static void test(int n){
        if(n>2){
            test(n-1);
        }else{
            System.out.println(n); // 2
            // 进入if 就不会执行else
        }
        //System.out.println(n);
        // 2 3 4
    }
}
package recursion;
// factorial
public class Demo01 {
    public static void main(String[] args) {
        int res = factorial(5);
        System.out.println(res);
    }
    public static int factorial(int i){
        if(i==1){
            return 1;
        }else{
            return factorial(i-1)*i;
        }
    }
}

递归必须向退出递归的条件逼近,否则会无限递归


迷宫问题

分析说明

/**
	1. map: the maze
	2. i,j represents map[i][j] --> start location
f ball arrives map[6][5], that means it finds the way, return true
	3. map[i][j] == 0 means this point has not been touched
	4. map[i][j] == 1 means this point is a block
	5. map[i][j] == 2 means the ball goes this point
	6. map[i][j] == 3 means this point has been arrived but this way doesn't work
	7. STRATEGY: go down -- right -- up -- left, if this point does not work, go back
*/
 public static boolean setWay(int[][] map,int i,int j){}

代码实现

  1. 二维数组创建迷宫
  2. 标识特殊点
  3. 递归走动
package recursion;

public class Maze {
    public static void main(String[] args) {
        // create a 2-d array mimic maze
        // map
        int[][] map = new int[8][7];
        // 1--wall block
        // assign 1 to up line and base line
        for (int i = 0; i < 7; i++) {
            map[0][i] = 1;
            map[7][i] = 1;
        }
        // assign 1 to right line and left line
        for (int j = 0; j < 8; j++) {
            map[j][0] = 1;
            map[j][6] = 1;
        }
        // assign 1 to wall block
        map[3][1] = 1;
        map[3][3] = 1;

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }

        setWay(map,1,1);
        System.out.println("play done");
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }
    }
    // recursion
    /**
     *
     * @param map
     * @param i start location
     * @param j
     * @return if find it, return true, otherwise return false
     */
    public static boolean setWay(int[][] map,int i,int j){
        if(map[6][5] == 2){ // find the path!
            return true;
        }else{
            if(map[i][j] == 0){ // if this point has not been arrived
                // go with strategy
                map[i][j] = 2; // assumed this way can work
                if(setWay(map,i+1,j)){ // go down
                    return true;
                }else if(setWay(map,i,j+1)){ // go right
                    return true;
                }else if(setWay(map,i-1,j)){ // go up
                    return true;
                }else if(setWay(map,i,j-1)){ // go left
                    return true;
                }else{ // this point can not work
                    map[i][j] = 3;
                    return false;
                }
            }else{ // if map[i][j]!=0 map[i][j] may be 1,2,3
                return false;
            }
        }
    }
}

八皇后问题

总共八个皇后在棋盘上,任意两个皇后都不能处在同一行、同一列或同一斜线上,问有多少种摆法?

思路分析

  1. 第一个皇后先放在第一行第一列
  2. 第二个皇后放在第二行第一列,判断是否可行,如果不可行,继续放在第二列、第三列,依次把所有的列都放完,找到一个合适的位置
  3. 继续放第三个皇后,还是第一列、第二列…,直到第八个皇后也能放在一个不冲突的位置,算是找到一个正确的解
  4. 当得到一个正确的解,栈回到上一个栈时,就会开始回溯,即将第一个皇后放到第一列的所有正确解都得到
  5. 然后回头继续第一个皇后放在第二列,继续循环1,2,3,4步骤

数据结构:一维数组表示棋盘 arr[8] = {0,4,7,5,2,6,1,3} arr的下标表示第几个皇后,arr[i] = val,val 表示第 i+1 个皇后,放在第 i+1行的第 val+1 列


代码实现

package recursion;


public class Queen8 {
    // define max means the num of queens
    int max = 8;
    // define an array store result, eg:arr = {0,4,7,5,2,6,1,3}
    int[] array = new int[max];
    static int count = 0;
    public static void main(String[] args) {
        // test
        Queen8 queen8 = new Queen8();
        queen8.check(0);
        System.out.println("total solution:  "+count);

    }

    // method put n-th queen
    // for each recursion, check has forloop, so here has traceback
    private void check(int n){
        if(n==max){ // n = 8, eight queens already done
            print();
            return;
        }
        // put into queen, determine whether it is conflict
        for(int i=0;i<max;i++){
            // current queen --> fist col of this row
            array[n] = i;
            // is this conflict? put n-th queen to i-th column
            if(judge(n)){
                // not conflict
                // put (n+1)-th queen: recursion
                check(n+1);
            }
            // if conflicts, continue go arr[n] = i; here i is i+1
            // that is putting n-th queen to next col in this row

        }
    }

    // when you put n-th queen, check if it has conflict on previous n-1 queen
    private boolean judge(int n){ // n-th queen
        for (int i = 0; i < n; i++) {
            if(array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] - array[i])){
                // array[i] == array[n]:determine whether n and previous n-1 queens are at the same column
                // Math.abs(n-i) == Math.abs(array[n] - array[i]): determine whether n-th queen hs the same slash with i-th queen
                return false;
            }
        }
        return true;
        
    }

    // method: print queens location
    private void print(){
        count++;
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }
}
  1. 定义变量 max:总共几个皇后

  2. 定义变量 array:一维数组存放解,arr[1] = {0,4,7,5,2,6,1,3}

    第一行皇后位置为列1;第二行皇后的位置为列5;第三行皇后的位置为列8…

  3. 定义变量 count:记录结果数量

  4. 定义方法 public void print():打印每一个结果(一维数组)

  5. 定义方法 public boolean judge(int n):判断第 n 个皇后与之前的皇后是否冲突

    array[i] == array[n]
    // 第n个皇后和第i个皇后在同一列
    Math.abs(n-i) == Math.abs(array[n] - array[i])
    // 第n个皇后后第i个皇后在同一斜线
    
  6. 定义方法 private void check(int n) : 先判断是否所有的皇后都安排完;将皇后放入数组,判断是否冲突,递归

    // 如果八个皇后都排过,就打印出来
    for(int i = 0;i<max;i++){
      arrar[n] = i;
      if(judge(n)){// 如果不冲突,判断第n+1个皇后
        check(n+1)}
      // 如果冲突的话,会返回到 arrar[n] = i; i变成i+1,即将第n个皇后放到该行的下一列继续进行判断
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值