首页 > 其他 > 详细

52. N-Queens II - Hard

时间:2019-08-25 10:42:59      阅读:89      评论: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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

 

use dfs / backtracking

time = O(n!), space = O(n)

class Solution {
    Set<Integer> usedCols = new HashSet<>();
    Set<Integer> diag1 = new HashSet<>();
    Set<Integer> diag2 = new HashSet<>();
    int count = 0;
    
    public int totalNQueens(int n) {
        helper(0, n);
        return count;
    }
    
    private void helper(int row, int n) {
        if(row == n) {
            count++;
            return;
        }
        
        for(int col = 0; col < n; col++) {
            if(isValid(row, col)) {
                usedCols.add(col);
                diag1.add(row + col);
                diag2.add(row - col);
                helper(row + 1, n);
                usedCols.remove(col);
                diag1.remove(row + col);
                diag2.remove(row - col);
            }
        }
    }
    
    private boolean isValid(int row, int col) {
        return !(usedCols.contains(col) || diag1.contains(row + col) || diag2.contains(row - col));
    }
}

 

52. N-Queens II - Hard

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

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