n-queens

The n-queens puzzle is the problem of placing n queens on an n×nchessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where'Q'and'.'both indicate a queen and an empty space respectively.


分析:查阅相关资料,得知需要行,列以及对角线都只有一个皇后

那么接下来就是遍历的过程,每次放置一个皇后,都要确定他的合法性


大神的妙用:  由于每行只有一个皇后,那么可以建立一个一维数组,代表每行那个唯一的皇后的位置

import java.util.*;
public class Solution {
    ArrayList<String[]> result=new ArrayList<>();
    public ArrayList<String[]> solveNQueens(int n) {
        if(n<=0){
            return result;
        }
        int[] cols=new int[n];
        for(int i=0;i<n;i++){
            cols[0]=i;
            dfs(cols,1);
        }
        return result;
    }
    public void dfs(int[] cols,int row){
	//当相等时,就证明已经产生了一个可行解
        if(row==cols.length){
            String[] str=new String[cols.length];
            for(int i=0;i<str.length;i++){
                str[i]="";
                for(int j=0;j<str.length;j++){
                    if(j==cols[i]){
                        str[i]+="Q";
                    }else{
                        str[i]+=".";
                    }
                }
            }
            result.add(str);
            return;
        }
        //判断row行的第i列是否符合,若符合,设置当前行皇后的坐标  继续判断下一行
        for(int i=0;i<cols.length;i++){
            if(isOK(cols,row,i)){
                cols[row]=i;
                dfs(cols,row+1);
            }
        }
    }
    //进行判断合法性  是否同一列,是否对角线
    public boolean isOK(int[] cols,int row,int col){
        if(cols==null){
            return false;
        }
        for(int i=0;i<row;i++){
            if(cols[i]==col||Math.abs(cols[i]-col)==Math.abs(row-i)){
                return false;
            }
        }
        return true;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值