【leetcode】【hard】52. N-Queens II

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.."]
]

題目鏈接:https://leetcode-cn.com/problems/n-queens-ii/

 

思路

法一:回溯法

思路和上一道n皇后問題用的一樣。

class Solution {
public:
vector<int> row;
vector<bool> col;
vector<bool> dir1;
vector<bool> dir2;
int res = 0;
    int totalNQueens(int n) {
        if(n<=0) return 0;
        if(n==1) return 1;
        row = vector<int>(n);
        col = vector<bool>(n, false);
        dir1 = vector<bool>(n*2-1, false);
        dir2 = vector<bool>(n*2-1, false);
        trace(n,0);
        return res*2;
    }
    void trace(int n, int idx){
        if(idx==n){
            ++res;
            return;
        }
        for(int j=0; j<n; ++j){
            if(idx==0 && j>=n/2) break;
            if(!col[j] && !dir1[j-idx+n-1] && !dir2[idx+j]){
                row[idx] = j;
                col[j] = true;
                dir1[j-idx+n-1] = true;
                dir2[idx+j] = true;
                trace(n, idx+1);
                row[idx] = -1;
                col[j] = false;
                dir1[j-idx+n-1] = false;
                dir2[idx+j] = false;
            }
        }
    }
};

法二:位運算

這個是在沒看懂。。哭了

等我其他題刷上來了再解決這個可惡的位運算。。。

參考:https://leetcode-cn.com/problems/n-queens-ii/solution/nhuang-hou-ii-by-leetcode/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章