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 Ruby (judge verdict: Accepted)

def solve(chess, remain_queens)
  if remain_queens == 0 then
    return true
  end

  cand_mass = collect(chess)
  cand_mass.each do |row, col|
    put_queen(row, col, chess)
    return true if solve(chess, remain_queens-1)
    remove_queen(row, col, chess)
  end
  return false
end

def collect(chess)
  candidates = []
  chess.each_with_index do |r, r_i|
    r.each_with_index do |c, c_i|
      candidates << [r_i, c_i] if chess[r_i][c_i] == 0
    end
  end
  return candidates
end

def put_queen(row, col, chess)
  do_queen(row, col, chess, 1)
end

def remove_queen(row, col, chess)
  do_queen(row, col, chess, -1)
end

def do_queen(row, col, chess, addition)
  chess[row][col] -= addition

  chess.each_with_index do |r, r_i|
    r[col] += addition unless r_i == row
  end
  chess[row].each_with_index do |c, c_i|
    chess[row][c_i] += addition unless c_i == col
  end

  r_i, c_i = row-1, col-1
  while r_i >= 0 && c_i >= 0 do
    chess[r_i][c_i] += addition
    r_i -= 1
    c_i -= 1
  end

  r_i, c_i = row+1, col-1
  while r_i <= 7 && c_i >= 0 do
    chess[r_i][c_i] += addition
    r_i += 1
    c_i -= 1
  end

  r_i, c_i = row+1, col+1
  while r_i <= 7 && c_i <= 7 do
    chess[r_i][c_i] += addition
    r_i += 1
    c_i += 1
  end

  r_i, c_i = row-1, col+1
  while r_i >= 0 && c_i <= 7 do
    chess[r_i][c_i] += addition
    r_i -= 1
    c_i += 1
  end
end

def show(chess)
  chess.each do |row|
    puts(row.map {|v| (v < 0) ? "Q" : "."}.join)
  end
end

# main
chess = []
8.times do
  chess << [0, 0, 0, 0, 0, 0, 0, 0]
end

n = gets.chomp.to_i
n.times do
  row, col = gets.chomp.split.map(&:to_i)
  put_queen(row, col, chess)
end

solve(chess, 8-n)
show(chess)