代码:
#include<iostream>
#include<vector>
using namespace std;
vector<vector<string> >res;
bool isValid(int row, int col, vector<string>&chessboard, int n)
{
int count = 0;
//检查列
for (int i = 0; i < row; i++)
{
if (chessboard[i][col] == 'Q')
{
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
{
if (chessboard[i][j] == 'Q')
{
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
{
if (chessboard[i][j] == 'Q')
{
return false;
}
}
return true;
}
void backtracking(int n, int row, vector<string>& chessboard)
{
if (row == n)
{
res.push_back(chessboard);
return;
}
for (int i = 0; i < n; i++)
{
if (isValid(row, i, chessboard, n))
{
chessboard[row][i] = 'Q';
backtracking(n, row + 1, chessboard);
chessboard[row][i] = '.';
}
}
}
void printRes()
{
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
{
cout << res[i][j] << endl;
}
cout << endl;
}
}
int main()
{
int n;
cin >> n;
vector<string>chessboard(n, string(n, '.'));
backtracking(n, 0, chessboard);
printRes();
return 0;
}