### 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:
vector<vector<string> > res;

vector<vector<string>> solveNQueens(int n) {

int *a=new int[n];
memset(a,0,sizeof(int)*n);
solve(a,n,0);
return  res;
}

void solve(int *a, int n,int index)
{
for(int i=0;i<n;i++)//对每个index 寻找第i列放皇后
{
if(isValid(a,n,index,i))//index i 行 列
{
a[index]=i;
if(index==n-1)
{
print(a,n);
a[index]=0;
return ;
}
solve(a,n,index+1);
a[index]=0;
}
}
}

void print(int *a, int n)
{
vector<string> path;
for(int i=0;i<n;i++)
{
string s(n,'.');
s[a[i]]='Q';
path.push_back(s);
}
res.push_back(path);
}

bool isValid(int *a,int n,int x,int y)
{
int col;
for(int i=0;i<x;i++)//行
{
col=a[i];//第i行，皇后在第col列
if(y==col) //同列
return false;
if((col-y)==(i-x))// 对角线'\'
return false;
if((col-y)==(x-i))// 对角线'/'
return false;
}
return true;
}
};

#### N-Queens N皇后问题 DFS

2015-08-18 20:11:28

#### leetCode 51.N-Queens (n皇后问题) 解题思路和方法

2015-07-13 13:23:15

#### Leetcode: N-Queens

2013-10-19 22:50:17

#### lintcode-N-Queen, N皇后问题

2016-08-14 22:35:05

#### N-Queens II 经典问题：8皇后问题 题解

2016-02-06 00:15:24

#### 【Leetcode】：51. N-Queens 问题 in JAVA

2016-04-25 19:16:59

#### leetcode hard模式专杀之51. N-Queens

2017-06-07 20:19:08

#### 【LeetCode】51.N-Queens(hard)解题报告

2018-01-13 00:20:41

#### [leetcode-51]N-Queens(java)

2015-08-03 09:06:27

#### N-Queens 题解

2016-02-06 00:26:46

## 不良信息举报

N-Queens N皇后放置问题 回溯法