AcWing 843. n-皇后问题
原题链接
中等
作者:
Fxzbed
,
2024-11-26 11:12:55
,
所有人可见
,
阅读 9
#include <iostream>
using namespace std;
int n;
char a[10][10];
bool isL[10], cros[20], cros_[20];
void bfs(int u) {
if (u == n) {
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++) {
if (a[i][j] == 'Q') printf("Q");
else printf(".");
}
puts("");
}
puts("");
return;
}
for (int i = 0; i < n; i ++) {
if (!isL[i] && !cros_[u - i + n] && !cros[u + i]) {
a[u][i] = 'Q';
cros_[u - i + n] = true;
cros[u + i] = true;
isL[i] = true;
bfs(u + 1);
a[u][i] = '.';
isL[i] = false;
cros_[u - i + n] = false;
cros[u + i] = false;
}
}
}
int main(void) {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++) {
cin >> a[i][j];
}
}
bfs(0);
return 0;
}