Description

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.

[leetcode] 51. N-Queens_参考文献


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个皇后在一个棋盘上,然后皇后上下左右对角线不能共线。输出所有的放置方案。

  • 这是一个典型的递归求解的问题,下面是一个经典的做法。由于棋盘的每一排只能放一个,所以用x的下表代表棋盘的行,x的值代表列,所以用一个一维的数组递归求解就行了,节省了空间,然后递归遍历的每个位置都需要检查一下是否跟以前的皇后的位置有冲突,找一个没有冲突的位置作为当前行的皇后的位置,主要思想就是这样的。

代码

class Solution {
int x[19];
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> out;
string s1(n,'.');
for(int i=0;i<n;i++){
out.push_back(s1);
}
solve(res,out,0,n);
return res;
}
void solve(vector<vector<string>>& res,vector<string> out,int start,int n){
if(start==n){
res.push_back(out);
return ;
}
for(int i=0;i<n;i++){
x[start]=i;
out[start][i]='Q';
if(check(start)){
solve(res,out,start+1,n);
}
out[start][i]='.';
}
}
bool check(int m){
for(int i=0;i<m;i++){
if(abs(x[m]-x[i])==abs(m-i)||x[m]==x[i]) return false;
}
return true;
}
};

参考文献

​[编程题]n-queens​