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> > solveNQueens(int n) {
vector<vector<string> > Array;
vector<int> ivec;
//初始化数组,使得 ivec[i] = i
for (int i = 0; i < n; ++i) {
ivec.push_back(i);
}
func(Array, ivec, 0, n);
return Array;
}
void func(vector<vector<string> > &Array, vector<int> &ivec, int start, int last) {
//判断是否到结尾,是就说明是全排列中的一种
if (start == last) {
//判断是否满足 皇后之间不能吃,斜对角线和反斜对角线
for (int i = 0; i < last; ++i) {
for (int j = i + 1; j < last; ++j) {
if (i - j == ivec[i] - ivec[j] || j - i == ivec[i] - ivec[j])
return;
}
}
//保存皇后位置
vector<string> tempvec;
for (int i = 0; i < last; ++i) {
string str;
for (int j = 0; j < ivec[i]; ++j) {
str += ".";
}
str += "Q";
for (int j = ivec[i] + 1; j < last; ++j) {
str += ".";
}
tempvec.push_back(str);
}
Array.push_back(tempvec);
return;
}
//循环加递归 做全排列
for (int i = start; i < last; ++i) {
swap(ivec[i], ivec[start]);
func(Array, ivec, start + 1, last);
swap(ivec[i], ivec[start]);
}
}
};