# LeetCode51. N-Queens（剑指offer38-3)

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.

Example:

Input: 4
Output: [
[".Q..",  // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.",  // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

N皇后：注意循环是指排列的col变动，从0开始；递归是指下一个string，row的变动。


class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> ret;
vector<string> myqueen(n,string(n,'.'));
Helper(ret,myqueen,n,0);
return ret;
}

void Helper(vector<vector<string>>&ret,vector<string> &myqueen,int n,int row){
if(row==n)
{
ret.push_back(myqueen);
return;
}
for(int col=0;col<n;col++)//排序的是col
{
if(!IsValid(myqueen,n,row,col))//基于条件对string进行排序。col是变量
continue;
myqueen[row][col]='Q';
Helper(ret,myqueen,n,row+1);//往myqueen的下一个string,所以是row+1
myqueen[row][col]='.';
}
}

bool IsValid(vector<string> myqueen,int n,int row,int col){
//row
//  for(int c = col; c >=0; c--)
//  {
//      if(myqueen[row][c]=='Q')
//      return false;
//  }
//因为已经Helper(row+1),所以一行中只有一个Q是固定了的。

//col
for(int r=row;r>=0;r--)
{
if(myqueen[r][col]=='Q')
return false;
}

//45°
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
{
if(myqueen[i][j]=='Q')
return false;
}

//135°
for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++)
{
if(myqueen[i][j]=='Q')
return false;
}

return true;
}
};