题目链接
vector<vector<string> > solveNQueens(int n) {
vector<vector<string>> solutions;
if (n == 0)
{
return solutions;
}
int* place_queen = new int[n];
for (int i = 0; i < n; i++)
{
place_queen[i] = -1;
}
int index = 0;
while (index >= 0)
{
place_queen[index]++;
if (place_queen[index] >= n)
{
place_queen[index] = -1;
index--;
if (index < 0)
{
break;
}
continue;
}
bool place_able = true;
for (int i = 0; i < index; i++)
{
if (place_queen[index] == place_queen[i]
|| place_queen[index] == (place_queen[i] + (index - i))
|| place_queen[index] == (place_queen[i] - (index - i)))
{
place_able = false;
break;
}
}
if (place_able == true)
{
index++;
if (index >= n)
{
vector<string> solution;
for (int row = 0; row < n; row++)
{
string line;
for (int col = 0; col < n; col++)
{
if (col == place_queen[row])
{
line += "Q";
}
else
{
line += ".";
}
}
solution.push_back(line);
}
solutions.push_back(solution);
index--;
place_queen[index] = -1;
index--;
}
}
}
return solutions;
}