zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    自主问题--KMP算法
    题解--luogu--CSP2019.S.Day2.T4--Emiya 家今天的饭
    浅谈——RMQ
    浅谈——LCA
    NOIP(si le)或者CSP初赛之——前序中序后序,前缀中缀后缀
    浅说——查分约束
    浅说——tarjan
    C++ RQNOJ 星门龙跃
    C++ 洛谷 1261:【例9.5】城市交通路网
    刷题
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12348408.html
Copyright © 2011-2022 走看看