LeetCode N-Queens

2 篇文章 0 订阅

原题链接在此:https://leetcode.com/problems/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.."]
]

Hide Tags
  Backtracking
Hide Similar Problems
  (H) N-Queens II










这是一道典型的NP问题,基本思路如下就是递归加回溯:

用递归处理子问题,当某一个子问题出错时就回溯到上一层。这类问题的时间复杂度都是指数量级的。

在子问题中,列出一种例子,判断当前情况是否合法,如果不合法就回到上一层,如果合法就DFS到下一层,当填满后就保存此正确结果。然后去掉最后添加的数,列举其他方法。但本题中不需要去掉就是因为此题是用一个一维数组代表棋盘,每个index代表行, value 代表列。

[2,0,1,3] 代表[0,2],[1,0],[2,1],[3,3]上有皇后。


但有几个问题需要注意,首先要注意返回类型是List<List<String>>,也就是List of List,在生成时一定要这么写

List<List<String>> res = new ArrayList<List<String>>();
否则会报错。

其次注意declare helper function 时,argument 要写成 

List<List<String>> res

还有就是用到了新的class StringBuilder, 其sb.append("Hello!")和sb.toString()非常好用。


AC Java:

</pre><pre name="code" class="java">public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<List<String>>();
        helper(n,0,new int[n],res);
        return res;
        
    }
    
    private void helper(int n, int cur, int[] row, List<List<String>> res){
        //cur stands for current row index
        if(cur == n){
            List<String> temp = new ArrayList<>();
            for(int j = 0; j<row.length;j++){
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i<row.length; i++){
                    if(row[j] != i) {
                        sb.append(".");
                    }else{
                        sb.append("Q");
                    }
                }
                temp.add(sb.toString());
            }
            res.add(temp);
            return;
        }
        
        //If we haven't reached the end
        for(int i = 0; i < n; i++){
              row[cur] = i;
              if(isValid(cur, row)){
                  helper(n,cur+1,row,res);
              }
        }
    
    }
    
    //Check if the current queens position is valid
    private boolean isValid(int cur, int[] row){
        for(int i = 0;i<cur;i++){
            if(row[cur] == row[i] || Math.abs(row[i]-row[cur]) == (cur-i)){
                return false;
            }
        }
        return true;
    }
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值