递归问题 java

package com.算法.递归;

public class 迷宫 {
    public static boolean flag;
    public static int[][] look; //储存地图
    public static boolean[][] book;//标记地图
    public static int[][] next={{0,1},{1,0},{0,-1},{-1,0}};
    public static void main(String[] args) { //从(1,1)到(7,5)
        look = new int[8][7];
        book = new boolean[8][7];
        for(int i=0;i<8;i++){
            look[i][0] = 1;
            look[i][6] = 1;
        }
        for(int i=0;i<7;i++){
            look[0][i] = 1;
            look[7][i] = 1;
        }
        look[2][1]=1;
        look[2][2]=1;
        look[1][4]=1;
        look[3][3]=1;
        look[1][1]=2;
        System.out.println("初始地图为:");
        for(int[] data :look){
            for(int temp :data){
                System.out.print(temp+" ");
            }
            System.out.println();
        }
        System.out.println("找到的路径:");
        dfs(1,1);
        if(flag){
            for(int[] data :look){
                for(int temp :data){
                    System.out.print(temp+" ");
                }
                System.out.println();
            }
        }
    }
    public static void dfs(int x,int y){
        if(x==6&&y==5){
            flag =true ;
            look[x][y]=2;
            return ;
        }else{
            for(int i=0;i<4;i++){
                int tx=x+next[i][0];
                int ty=y+next[i][1];
                if(!book[tx][ty]&&look[tx][ty]==0){
                    look[tx][ty]=2;
                    book[tx][ty]=true;
                    dfs(tx,ty);
                    if(flag){
                        return ;
                    }
                    look[tx][ty]=0;
                    book[tx][ty]=false;
                }
            }
        }
    }
}

package com.算法.递归;

public class 八皇后 {
    public static int ans;
    public static int[] array=new int[8]; //储存每行皇后所在的位置
    public static void main(String[] args) {
    huangHou(0);
    System.out.println("一共有"+ans+"中放置方法");
    }
    public static void huangHou(int x){
        if(x==8){
            ans++;
            return ;
        }else{
            for(int i=0;i<8;i++){
                array[x]=i;
                if(ok(x)){
                    huangHou(x+1);
                }
            }
        }
    }
    public static boolean ok(int n){ //判断这个位置是不是可以放置
        for(int i=0;i<n;i++){
            if(array[i]==array[n]||Math.abs(n-i)==Math.abs(array[i]-array[n])){
                return false;
            }
        }
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值