leetcode[51]N-Queens

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.."]
]
class Solution {
public:
void init(vector<string> &temp, int n)
{
    string strtemp(n,'.');
    temp.insert(temp.end(),n,strtemp);
    return;
}
bool checkij(vector<string> &temp, int i, int j)
{
    for (int ii=i-1,jleft=j-1;ii>=0&&jleft>=0;ii--,jleft--)
    {
        if(temp[ii][jleft]=='Q')return false;
    }
    for (int ii=i-1,jright=j+1;ii>=0&&jright<temp.size();ii--,jright++)
    {
        if(temp[ii][jright]=='Q')return false;
    }
    for (int k=0;k<temp.size();k++)
    {
        if (k!=j&&temp[i][k]=='Q')return false;
        if (k!=i&&temp[k][j]=='Q')return false;
    }
    return true;
}
bool solveOne(vector<vector<string>> &res,vector<string> &temp,int n, int index)
{
    if(index==n)
    {
        res.push_back(temp);
        return true;
    }
    for (int j=0;j<n;j++)
    {
        temp[index][j]='Q';
        if (checkij(temp,index,j))
        {
            solveOne(res,temp,n,index+1);
        }
        temp[index][j]='.';    
    }
}
vector<vector<string>> solveNQueens(int n) 
{
    vector<vector<string>> res;
    vector<string> temp;
    init(temp,n);
    for(int i = 0; i < n; i++) {
        temp[0][i] = 'Q';
        solveOne(res, temp, n, 1);
        temp[0][i] = '.';
    }
    return res;
}
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283547.html