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

object Main {
    def queens(n: Int, fixed: List[(Int, Int)]): List[List[(Int, Int)]] = {
        def placeQueens(k: Int): List[List[(Int, Int)]] = {
            if(k == -1) List(List())
            else
                for {
                    queens <- placeQueens(k - 1)
                    col <- 0 to n - 1
                    queen = (k, col)
                    if isSafe(queen, queens)
                } yield queen :: queens
        }
         placeQueens(n - 1).filter(qs => check(fixed, qs))
    }

    def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) = {
        queens.forall(q => !inCheck(queen, q))
    }

    def inCheck(q1: (Int, Int), q2: (Int, Int)) = {
        q1._1 == q2._1 ||
        q1._2 == q2._2 ||
        (q1._1 - q2._1).abs == (q1._2 - q2._2).abs
    }

    def check(fixed: List[(Int, Int)], queens: List[(Int, Int)]) =
        fixed.forall(q => queens.contains(q))

    def main(args:Array[String]) = {
        val sc = new java.util.Scanner(System.in)
        val n = sc.nextInt
        val fixed = List.fill(n)(sc.nextInt, sc.nextInt)
        for(qs <- queens(8, fixed)) {
            for(y <- 0 to 7) {
                for(x <- 0 to 7) {
                    print(if(qs.contains((y, x))) "Q" else ".")
                }
                println
            }
        }
    }
}