描述
n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。
給定一個整數n,返回所有不同的n皇后問題的解決方案。
每個解決方案包含一個明確的n皇后放置佈局,其中“Q”和“.”分別表示一個女王和一個空位置。
樣例
對於4皇后問題存在兩種解決的方案:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
挑戰
你能否不使用遞歸完成?
思路
只能AC 90%。
#ifndef C33_H
#define C33_H
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
/*
* @param n: The number of queens
* @return: All distinct solutions
*/
vector<vector<string>> solveNQueens(int n) {
// write your code here
vector<int> nums(n, 0);
vector<vector<string>> res;
for (int i = 0; i < n; ++i)
nums[i] = i;
do{
bool flag = true;
string str(n, '.');
vector<string> vec(n, str);
for (int i = 0; i < n - 1; ++i)
{
if (!flag)
break;
for (int j = i + 1; j < n; ++j)
{
if (i - j == nums[i] - nums[j] || i - j == nums[j] - nums[i])
{
flag = false;
break;
}
}
}
if (flag)
{
for (int i = 0; i < n; ++i)
{
vec[i][nums[i]] = 'Q';
}
res.push_back(vec);
}
} while (next_permutation(nums.begin(), nums.end()));
return res;
}
};
#endif