码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 51. N-Queens

时间:2020-02-23 09:44:19      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:list   public   str   for   board   help   code   config   example   

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.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

class Solution {
    public List<List<String>> solveNQueens(int n) {       
        List<List<String>> res = new ArrayList<>();
        List<String> list = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        helper(res, list, 0, n);
        return res;
    }
    
    private void helper(List<List<String>> res, List<String> list, int level, int n) {
        if (level == n) {
            res.add(new ArrayList<>(list));
            return;
        }
        char[] charArr = new char[n];
        Arrays.fill(charArr, ‘.‘);
        for (int i = 0; i < n; i++) {
            charArr[i] = ‘Q‘;
            if (isValid(i, list)) {
                list.add(new String(charArr));
                helper(res, list, level + 1, n);
                list.remove(list.size() - 1);
            }
            charArr[i] = ‘.‘;
        }
    }
    
    private boolean isValid(int column, List<String> list) {
        int row = list.size();
        for (int i = 0; i < row; i++) {
            String cur = list.get(i);
            int col = cur.indexOf("Q");
            if (col == column || row - i == Math.abs(col - column)) {
                return false;
            }
        }
        return true;
    }
}

 

[LC] 51. N-Queens

标签:list   public   str   for   board   help   code   config   example   

原文地址:https://www.cnblogs.com/xuanlu/p/12348408.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!