首页 > 其他 > 详细

51. N-Queens - Hard

时间:2019-08-25 09:46:38      阅读:87      评论:0      收藏:0      [点我收藏+]

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.

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.

 

use dfs

time = O(n! * n^2), space = O(n)

class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        Set<Integer> usedCols = new HashSet<>();
        Set<Integer> diag1 = new HashSet<>();
        Set<Integer> diag2 = new HashSet<>();
        dfs(usedCols, diag1, diag2, 0, n, new ArrayList<>(), res);
        return res;
    }
    
    private void dfs(Set<Integer> usedCols, Set<Integer> diag1, Set<Integer> diag2, 
                     int level, int n, List<Integer> pos, List<List<String>> res) {
        if(level == n) {
            List<String> list = new ArrayList<>();
            for(int idxQ : pos) {
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i < n; i++) {
                    if(i == idxQ) {
                        sb.append(‘Q‘);
                    } else {
                        sb.append(‘.‘);
                    }
                }
                list.add(sb.toString());
            }
            res.add(list);
            return;
        }
        
        for(int j = 0; j < n; j++) {
            if(isValid(level, j, usedCols, diag1, diag2)) {
                pos.add(j);
                usedCols.add(j);
                diag1.add(j + level);
                diag2.add(level - j);
                dfs(usedCols, diag1, diag2, level + 1, n, pos, res);
                pos.remove(pos.size() - 1);
                usedCols.remove(j);
                diag1.remove(j + level);
                diag2.remove(level - j);
            }
        }
    }
    
    private boolean isValid(int row, int col, Set<Integer> usedCols, Set<Integer> diag1, Set<Integer> diag2) {
        return !usedCols.contains(col) && !diag1.contains(row + col) && !diag2.contains(row - col);
    }
}

 

51. N-Queens - Hard

原文:https://www.cnblogs.com/fatttcat/p/11406800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!