[LC] 51. N-Queens

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 51. N-Queens相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 51. N-Queens

[Lintcode]33. N-Queens/[Leetcode]51. N-Queens

51. N-Queens

51. N-Queens

51. N-Queens

51. N-Queens