Maze back and eight queens problem

The concept of recursion

Simply put: the recursive method that calls itself, each call passing in the different variables, recursion can help programmers to solve complex problems, and can make the code becomes simple

package recusion;

public class RecursionTest {

    public static void main(String[] args) {
        test(5);
        int i = factorial(5);
        System.out.println(i);
    }
    //打印问题
    //当程序执行到一个方法时,就会开辟一个独立的栈空间
    public static void test(int n) {
        if(n>2) {
            test(n-1);
        }
        System.out.print("n="+n+" ");//n=2 n=3 n=4 n=5 
    }
    //阶乘问题
    public static int factorial(int n) {
        if( n == 1) {
            return 1;
        }else {
            return factorial(n-1)*n;
        }
    }
}

imgimg

Recursive important rules you need to follow

1. execute a method, it creates a separate space (stack space) of new protected

2. The method of local variables are independent and do not affect each other, if the amount used in the process is the type of variable references, you will share the type of reference data

3. recursive approach to the conditions must withdraw recursion, or is infinite recursion,

4. When a method is finished, or encountered return, will return, observe who call, who will return the results to the same time when the method completes or returned, this method also is finished (if a stack code execution finished is returned to the caller)

Maze back problem

package recusion;

import java.util.ArrayList;
import java.util.List;

public class MiGong {

    public static void main(String[] args) {
        //先创建一个二维数组,模拟迷宫
        //地图
        //map[0][0]
        
        List<Integer> ls = new ArrayList<Integer>();
        
        int[][] map = new int[8][7];
        //使用1表示墙
        //上下全部置为1,用来作为迷宫的墙
        for(int i=0; i<7;i++) {
            map[0][i]=1;
            map[7][i]=1;
        }
        for(int i=0;i<8;i++) {
            map[i][0]=1;
            map[i][6]=1;
        }
        //设置挡板
        map[3][1]=1;
        map[3][2]=1;
//      for(int i=0;i<8;i++) {
//          for(int j=0;j<7;j++) {
//              System.out.print(map[i][j]+" ");
//          }
//          System.out.println();
//      }
        System.out.println("========================");
        setWay(map,1,1);
        //输出新的地图
        for(int i=0;i<8;i++) {
            for(int j=0;j<7;j++) {
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }

    }

    //使用递归回溯来归小球找路
    //1.map 表示地图
    //2.i,j表示从地图的那个位置开始出发
    //3.如果小球能到map[6][5]位置,则说明通路找到
    //4.约定:当map[i][j]为0表示该定没有走过  当为1表示墙  为2表示通路可以走;3表示改点已经走过,但是走不通
    //5.在走迷宫时,需要确定一个策略 下 ->右 ->上->左,如果改点走不通,在回溯
    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 {
                return false;
            }
        }
    }

}

8 queens problem

Eight queens problem is to chess as a background question: How can placing eight queens on a chess board 8 × 8, so that a queen can not eat any other directly Queen? For this purpose, any two Queens are not the same in the transverse, longitudinal or diagonal lines.

Eight queens problem analysis of thinking

  1. The first Queen's first put the first column of the first row
  2. The second Queen on the first column of the second row, and then determine whether to attack each other, attack each other if it continues in the second column, third row, followed by all the columns are done and find a suitable
  3. Queen continues the third, or the first column, second row .... until eight queens can not be placed in a position of conflict, it is found a correct solution
  4. When to get a correct solution, on the stack to fall back to a stack that will begin to backtrack, the first is about a queen, all right solution into the first column, all get
  5. Then put back to continue with a second column Queen, continues to loop back step performed 1,2,3,4

arr [i] = val, val i + 1 represents the Queen, val + 1 on the first column of row i + 1

package recusion;

import java.lang.reflect.Array;

public class Queue8 {
    int max = 8;
    int[] array = new int[max];
    static int count=0;
    public static void main(String[] args) {
        Queue8 queue8 = new Queue8();
        queue8.check(0);
        System.out.println(count);
        
    }
    //编写一个方法,放置第n个皇后
    private void check(int n) {
        if(n == max) {
            print();
            return;
        }
        //依次放入皇后,判断是否冲突
        for(int i=0;i<max;i++) {
            array[n]=i;
            //判断当放置第n个皇后到i列时,是否冲突
            if(judge(n)) {//不冲突
                //接着放n+1个皇后,即开始递归
                check(n+1);
            }
            
            //如果冲突,就继续执行array[n]=i;即将第n个皇后,放置在本行的后移的一个位置
        }
    }
    //查看当我们放置第n个皇后,就去检测该皇后是否和前面已经摆放的皇后冲突
    //array[i]==array[n]表示判断第n个皇后是否和前面的n-1个皇后在同一列
    //Math.abs(n-i)==Math.abs(array[n]-array[i]))表示判断第n个皇后是否和第i皇后是否在同一个斜线
    private boolean judge(int n) {
        for(int i=0;i<n;i++) {
            if(array[i]==array[n]||Math.abs(n-i)==Math.abs(array[n]-array[i])) {
                return false;
            }
        }
        return true;
    }
    
    //写一个方法,可以将皇后摆放的位置输出
    private void print() {
        count++;
        for(int i=0;i<array.length;i++) {
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }
}

Guess you like

Origin www.cnblogs.com/train99999/p/11116649.html