leetcode-51. N-Queens

126 篇文章 0 订阅

leetcode-51. N-Queens

题目:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard 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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],

[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]

就是典型的n皇后问题,如此经典的题目能不能做出来跟聪明无关,唯手熟尔。
总的来说分三部分

  • 一部分用来判断终止条件,即需要判断第len行,并且将boolean转换成List<String>因为java在做String操作的时候实际上是很慢的,这个是java使用习惯的问题了。这个答案超过了72%的答案运算结果。显然是因为使用了boolean[][]而非String
  • 第二部分是迭代条件,for循环内表示当前考虑的行数,len表示列数
  • 第三部分就是判断当前i行和len列是否可以填充true。
public class Solution {
    public List<List<String>> solveNQueens(int n) {

        List<List<String>> ret = new ArrayList<List<String>>();
        boolean [][] mat = new boolean[n][n];
        helper(ret,mat,0);
        return ret;
    }

    private void helper(List<List<String>> ret, boolean[][] mat,int len){
        if(len==mat.length){
            ArrayList<String> tmp = new ArrayList<String>();
            for(boolean[] list : mat){
                StringBuilder sb = new StringBuilder();
                for(boolean f : list)
                    if(f)
                        sb.append("Q");
                    else
                        sb.append(".");
                tmp.add(sb.toString());
            }
            ret.add(tmp);
            return ;
        }

        for(int i=0;i<mat.length;i++){
            if(verify(mat,len,i)){
                mat[len][i] = true;
                helper(ret,mat,len+1);
                mat[len][i] = false;
            }
        }
    }

    private boolean verify(boolean[][] mat, int ni , int nj){
        for(int i = 0 ; i<ni ; i++){
            if(mat[i][nj]) return false;
            if(ni-i-1>=0 && nj-i-1>=0 && mat[ni-i-1][nj-i-1]) return false;
            if(ni-i-1>=0 && nj+i+1<mat.length && mat[ni-i-1][nj+i+1]) return false;
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值