1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <iostream>
using namespace std;
const int N = 10;
int n; bool row[N], col[N], dg[N], udg[N]; char g[N][N];
void dfs(int x, int y, int s) { if (s > n) { return; } if (y == n) { y = 0, x++; } if (x == n) { if (s == n) { for (int i = 0; i < n; i++) { puts(g[i]); } puts(""); } return; } dfs(x, y + 1, s);
if (!row[x] && !col[y] && !dg[n + y - x] && !udg[x + y]) { row[x] = col[y] = dg[n + y - x] = udg[x + y] = true; g[x][y] = 'Q'; dfs(x, y + 1, s + 1); g[x][y] = '.'; row[x] = col[y] = dg[n + y - x] = udg[x + y] = false; } }
int main() { cin >> n;
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { g[i][j] = '.'; } }
dfs(0, 0, 0);
return 0; }
|