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)

class Table
  def initialize
    @t = []
    8.times do |i|
      @t << Array.new(8, 0)
    end
  end
  def get(x, y)
    @t[y][x]
  end
  def set(x, y)
    @t[y][x] = 1
    8.times do |i|
      8.times do |j|
        if @t[i][j] == 0 && takable?(x, y, j, i)
          @t[i][j] = 2
        end
      end
    end
  end
  def takable?(x1, y1, x2, y2)
    r = (Math.atan2(y2 - y1, x2 - x1) * 180.0 / Math::PI).to_i
    return true if r % 45 == 0
    return false
  end
  def to_s
    @t.map{|row| row.map{|col| if col == 1 then 'Q' else '.' end }.join('') }.join("\n")
  end
end

n = STDIN.gets.chomp.to_i
$default_queens = []
n.times do |i|
  y, x = STDIN.gets.chomp.split(' ').map(&:to_i)
  $default_queens << [x, y]
end

def default_table
  table = Table.new
  $default_queens.each do |q|
    table.set(q[0], q[1])
  end
  table
end

queue = []
queue << []

while true do
  table = default_table
  queens = queue.shift
  last = nil
  queens.each do |q|
    table.set(q[0], q[1])
    last = q
  end
  if queens.size + $default_queens.size == 8
    puts table.to_s
    exit
  end
  8.times do |y|
    next if last && last[1] > y
    8.times do |x|
      next if last && last[1] == y && last[0] >= x
      next if table.get(x, y) != 0
      new_queens = Marshal.load(Marshal.dump(queens))
      new_queens << [x, y]
      queue << new_queens
    end
  end
end