Leetcode N皇后

N皇后

题目描述:

n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
提示:
   1 <= n <= 9
   皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上

题目链接

示例

在这里插入图片描述

class Solution {
    private List<List<String>> result;
    private List<String> temp;
    private String space;
    private int n;
    public List<List<String>> solveNQueens(int n) {
        // 初始化
        this.result = new ArrayList<List<String>>();
        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 this.result;
    }
    private void Backtracking(int count){
        if(count == this.n){
            List<String> temp = new ArrayList<String>(); // 局部变量
            for(int i = 0 ; i<n ; i++) temp.add(this.temp.get(i));
            this.result.add(temp);
            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;
    }
}

典型的回溯算法,这里采用行优先,每一层都遍历所有列位置,如果该层当前列和前面所有的皇后有冲突(行、纵、斜位置具有皇后),则直接跳过当前列,继续遍历下一列,如果该层所有列都遍历完毕,但是都没有可行解,则回溯到上一层,然后开始上一层的下一列,重复以上步骤,直到到达最后一层都具有可行解即可。读者有疑问的地方,欢迎留言。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值