51. N-Queens 52. N-Queens II *HARD*

1. 求所有解

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.

For example,
There exist two distinct solutions to the 4-queens puzzle:

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

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
void insert(vector<vector<string>> &ans, vector<int> q, int n)
{
    vector<string> v(n, string(n, '.'));
    for(int i = 0; i < n; i++)
        v[i][q[i]] = 'Q';
    ans.push_back(v);
}
void helper(vector<vector<string>> &ans, vector<int> q, int n, int k)
{
    if(k == n)
    {
        insert(ans, q, n);
        return;
    }
    int i, j;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < k; j++)
        {
            if(q[j] == i || abs(j-k) == abs(q[j]-i))
                break;
        }
        if(j < k)
            continue;
        q[k] = i;
        helper(ans, q, n, k+1);
    }
}
vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> ans;
    vector<int> q(n, -1);
    for(int i = 0; i < n; i++)
    {
        q[0] = i;
        helper(ans, q, n, 1);
    }
    return ans;
}

2. 求解的个数

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

void helper(int &ans, vector<int> q, int n, int k)
{
    if(k == n)
    {
        ans++;
        return;
    }
    int i, j;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < k; j++)
        {
            if(q[j] == i || abs(j-k) == abs(q[j]-i))
                break;
        }
        if(j < k)
            continue;
        q[k] = i;
        helper(ans, q, n, k+1);
    }
}
int totalNQueens(int n) {
    int ans = 0;
    vector<int> q(n, -1);
    for(int i = 0; i < n; i++)
    {
        q[0] = i;
        helper(ans, q, n, 1);
    }
    return ans;
原文地址:https://www.cnblogs.com/argenbarbie/p/5265909.html