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;
        }
    }
  • 相关阅读:
    django创建项目,一个简单的登录。
    MySQL下载与安装
    查看拉去代码时候的git账号密码
    Springmvc-组件
    转发与重定向
    springMVC-常用注解
    springMVC-请求参数绑定
    SpringMVC-RequestMapping注解
    JAVA-异常处理
    springMVC-入门案例
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12348408.html
Copyright © 2011-2022 走看看