• 52. N-Queens II


    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));
        }
    }
  • 相关阅读:
    Objective C 总结(十):Conventions
    Objective C 总结(九):Errors
    iOS 关于传值
    iOS UIImage剪切圆形
    iOS 触摸的位置放一个大头针
    iOS开发之各种动画各种页面切面效果
    AFNetworking2.4.1 解析
    iOS网络协议----HTTP/TCP/IP浅析
    ios 开发日记 9
    ios开发日记
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11406816.html
Copyright © 2020-2023  润新知