int n; constint N = 10; bool row[N], col[N], dg[N], ndg[N]; char g[N][N];
voiddfs(int r, int c, int s) { // the colums overflows, set to the next row if (c >= n) { c = 0; ++r; } if (r >= n) { if (s >= n) { // consider a valid solution for (int i = 0; i < n; ++i) { cout << g[i] << endl; } cout << endl; } return; }
// try not put queen g[r][c] = '.'; dfs(r, c + 1, s); // try put queen if (!row[r] && !col[c] && !dg[r + c] && !ndg[r - c + n]) { g[r][c] = 'Q'; row[r] = col[c] = dg[r + c] = ndg[r - c + n] = true; // step into next columns dfs(r, c + 1, s + 1); // back track to restore context g[r][c] = '.'; row[r] = col[c] = dg[r + c] = ndg[r - c + n] = false; } }
intmain() { cin >> n; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { g[i][j] = '.'; } } dfs(0, 0, 0); }