八皇后问题

代码基本根书中一摸一样,自己很难想出这么简洁精美的算法。用到了递归和回溯的思想。核心方法是check方法。

package indi.tom.Algorithm.recursion;

import java.sql.SQLOutput;

/**
 * @Author Tom
 * @Date 2019/11/10 20:11
 * @Version 1.0
 * @Description Eight queens issue.
 */
public class Queen8 {
    //the queens location, the index of the array represent the line number
    //the value of the array element represents the column of the queen location in the chessboard
    private static int[] queens = new int[8];
    //the number of answers
    private static int count;

    public static void main(String[] args) {
        check(0);
        System.out.println("totally there are " + count + " possibilities.");

    }

    //the final method to calculate all the possibility of the 8 queen's location.
    public static void check(int n){
        if(n == 8){
            //means find a possibility, print the current queen array
            print();
            return;
        }
        for (int i = 0; i < 8; i++) {
            queens[n] = i;
            if(judge(n)){
                check(n+1);
            }
        }
    }
    //print the current queens location
    public static void print(){
        count++;
        for (int i = 0; i < queens.length; i++) {
            System.out.printf("%d\t",queens[i]);
        }
        System.out.println();
    }
    //determine whether the given number of queen's location is conflict with the previous queens
    public static boolean judge(int n){
        for (int i = 0; i < n; i++) {
            if(queens[i] == queens[n] || Math.abs(n-i) == Math.abs(queens[n] - queens[i])){
                return false;
            }
        }
        return true;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值