Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

8 Queens Problem

The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.

For a given chess board where $k$ queens are already placed, find the solution of the 8 queens problem.

Input

In the first line, an integer $k$ is given. In the following $k$ lines, each square where a queen is already placed is given by two integers $r$ and $c$. $r$ and $c$ respectively denotes the row number and the column number. The row/column numbers start with 0.

Output

Print a $8 \times 8$ chess board by strings where a square with a queen is represented by 'Q' and an empty square is represented by '.'.

Constraints

There is exactly one solution

Sample Input 1

2
2 2
5 3

Sample Output 1

......Q.
Q.......
..Q.....
.......Q
.....Q..
...Q....
.Q......
....Q...

Solution in JavaScript (judge verdict: Accepted)

//config = { input: 'tmp', newline: '\r\n' }; // win
config = { input: '/dev/stdin', newline: '\n' }; // linux

const assert = require('assert');

const SIZE = 8;

rc = require('fs').readFileSync(config.input, 'ascii')
  .trim()
  .split(config.newline);
k = rc.shift();

b = new Array(SIZE);
function getInitialRow() {
  var res = new Array(SIZE), i;
  for (i = 0; i < SIZE; i++) res[i] = false;
  return res;
}
for (i = 0; i < SIZE; i++) b[i] = getInitialRow();

rest_row = getInitialRow();
rest_col = getInitialRow();
cnt = 0;

function place(r, c) {
  assert(!rest_row[r]);
  assert(!rest_col[c]);
  assert(!b[r][c]);
  assert(cnt < SIZE);
  rest_row[r] = true;
  rest_col[c] = true;
  b[r][c] = true;
  cnt++;
}

function remove(r, c) {
  assert(rest_row[r]);
  assert(rest_col[c]);
  assert(b[r][c]);
  assert(cnt > 0);
  rest_row[r] = false;
  rest_col[c] = false;
  b[r][c] = false;
  cnt--;
}

function diagonal_check(r, c) {
  var r_init = r, c_init = c;
  while (r > 0 && c > 0) { r--; c--; if (b[r][c]) return false; }
  r = r_init, c = c_init;
  while (r > 0 && c < SIZE - 1) { r--; c++; if (b[r][c]) return false; }
  r = r_init, c = c_init;
  while (r < SIZE - 1 && c > 0) { r++; c--; if (b[r][c]) return false; }
  r = r_init, c = c_init;
  while (r < SIZE - 1 && c < SIZE - 1) { r++; c++; if (b[r][c]) return false; }
  return true;
}

for (i in rc) {
  ary = rc[i].split(' ');
  place(ary[0], ary[1]);
}

function find() {
  var i, j;
  if (cnt === 8) return true;
  for (i in rest_row) {
    if (rest_row[i]) continue;
    for (j in rest_col) {
      if (rest_col[j]) continue;
      if (!diagonal_check(i, j)) continue;
      place(i, j);
      if (find()) return true;
      remove(i, j);
    }
  }
  return false;
}

find();
for (i in b) {
  console.log(
    b[i].map(function (flag) { return flag ? 'Q' : '.'; })
        .join(''));
}