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 ChessBoard
  attr_reader :queens

  def initialize
    @queens = []
  end

  def put_queen(queen)
    @queens << queen
  end

  def search_answer
    candidate_rows = (0..7).to_a - @queens.map(&:row)
    candidate_cols = (0..7).to_a - @queens.map(&:col)
    candidate_queens = candidate_rows.product(candidate_cols).map{|row, col| Queen.new(row, col)}
    @queens = calculate(@queens, candidate_queens)
  end

  def calculate(placed_queens, candidate_queens)
    if placed_queens.length == 8
      return placed_queens
    end
    while !candidate_queens.empty?
      current_queen = candidate_queens.shift
      if placed_queens.all?{|queen| queen.independent(current_queen)}
        answer = calculate(placed_queens + [current_queen], candidate_queens.select{|queen| queen.independent(current_queen)})
        if answer
          return answer
        end
      end
    end
  end

  def print
    (0..7).each do |row|
      queen = @queens.find{|q| q.row == row}
      if !queen
        puts ("." * 8)
      else
        puts ("." * 8).tap{|line| line[queen.col] = "Q"}
      end
    end
  end
end

class Queen
  attr_reader :row, :col

  def initialize(row, col)
    @row = row
    @col = col
  end

  def independent(other)
    (@row != other.row) && (@col != other.col) && ((@row - other.row).abs != (@col - other.col).abs)
  end
end

board = ChessBoard.new

k = gets.to_i
k.times do
  r, c = gets.split(" ").map(&:to_i)
  queen = Queen.new(r, c)
  board.put_queen(queen)
end

board.search_answer
board.print