Leetcode N皇后II

N皇后II

题目描述:

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回 n 皇后问题不同的解决方案的数量。
提示:
   1 <= n <= 9
   皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上

题目链接

class Solution {
    private int result;
    private List<String> temp;
    private String space;
    private int n;
    public int totalNQueens(int n) {
        // 初始化
        this.temp = new ArrayList<String>();
        this.n = n;
        this.space = "";
        for(int i = 0 ; i<n ; i++) this.space += ".";
        for(int i = 0 ; i<n ; i++){
            this.temp.add(space);
        }
        // 回溯算法
        Backtracking(0); // 行优先
        return result;
    }
    private void Backtracking(int count){
        if(count == this.n){
            this.result ++ ;
            return;
        }
        for(int i = 0 ; i<this.n ; i++){
            if(check(count,i)){
                String temp = this.temp.get(count).substring(0,i)+"Q"
                +this.temp.get(count).substring(i+1,this.n); // 局部变量
                this.temp.set(count,temp);
                Backtracking(count+1);
                this.temp.set(count,this.space); // 还原
            }
        }
    }
    private boolean check(int x,int y){
        for(int i = 0 ; i<x ; i++){ // 行遍历
            for(int j = 0 ; j<this.n ; j++){ // 列遍历
                if(this.temp.get(i).charAt(j) == 'Q'
                 &&( Math.abs(y-j) == Math.abs(x-i) // 斜线上相互攻击
                 || j == y)) // 纵线上相互攻击
                 return false; 
            }
        }
        return true;
    }
}

典型的回溯算法,这题读者只要能自己独立解决该题,一般这题就没有问题了,如果读者有疑问的地方,欢迎你的留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值