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)

import scala.io.StdIn.{readLine, readInt}
import scala.util.control.Breaks
import scala.collection.mutable.BitSet

object Main {
  val b = new Breaks

  def check(board:Array[Array[String]], i:Int, j:Int) = {
    var k = i
    var l = j
    var flg = board(i)(j) == "."

    while(flg && k>=0 && l>=0) {
      if(board(k)(l)!=".") flg = false
      k-=1;l-=1
    }

    k = i;l = j
    while(flg && k<8 && l<8) {
      if(board(k)(l)!=".") flg = false
      k+=1;l+=1
    }

    k = i;l = j
    while(flg && k<8 && l>=0) {
      if(board(k)(l)!=".") flg = false
      k+=1;l-=1
    }

    k = i;l = j
    while(flg && k>=0 && l<8) {
      if(board(k)(l)!=".") flg = false
      k-=1;l+=1
    }
    flg
  }

  def scan(board:Array[Array[String]],x:BitSet,y:BitSet):Boolean = {
    if(!x.isEmpty || !y.isEmpty) {
      var flg = false
      b.breakable {
        for(i<-x) {
          for(j<-y) {
            if(check(board,i,j)) {
              board(i)(j)="Q"
              if(scan(board,x-i,y-j)) {
                flg = true
                b.break
              } else {
                board(i)(j)="."
              }
            }
          }
        }
      }
      flg
    } else {
      true
    }
  }

  def main(args:Array[String]) = {
    val n = readInt
    val board = Array.ofDim[String](8,8)
    val x = BitSet(0,1,2,3,4,5,6,7)
    val y = BitSet(0,1,2,3,4,5,6,7)
    for(i<-0 to 7;j<-0 to 7) board(i)(j) = "."

    for(i<-0 until n) {
      val s = readLine.split(" ").map(_.toInt)
      board(s(0))(s(1)) = "Q"
      x -= s(0)
      y -= s(1)
    }
    scan(board,x,y)
    board.foreach( e=> println(e.mkString("")) )
  }
}