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
| #include<iostream> using namespace std;
const int N = 20; int n; char g[N][N]; bool row[N],col[N],dg[N],udg[N];
void dfs(int x,int y,int queen){ if(y == n) y = 0,x ++; if(x == n) { if(queen == n) { for(int i = 0;i<n;i++) puts(g[i]); puts(""); } return; } dfs(x, y+1, queen); if(!row[x] && !col[y] && !dg[x+y] && !udg[x-y+n]){ g[x][y] = 'Q'; row[x] = col[y] = dg[x+y] = udg[x-y+n] = true; dfs(x,y+1,queen+1); row[x] = col[y] = dg[x+y] = udg[x-y+n] = false; g[x][y] = '.'; } }
int main(){ cin >> n; dfs(0,0,0); return 0; }
|