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

fun main(args: Array<String>) = p17()

fun p17() {
    data class Rc(val row: Int, val column: Int)

    val k = readLine()!!.toInt()
    val inputs = Array(k) {
        val (r, c) = readLine()!!.split(' ').map { it.toInt() }
        Rc(r, c)
    }

    fun isValid(perm: List<Int>): Boolean {
        val leftToUp = mutableSetOf<Int>()
        val leftToDown = mutableSetOf<Int>()
        perm.forEachIndexed { row, column ->
            if (!leftToUp.add(row + column)) return false
            if (!leftToDown.add((7 - row) + column)) return false
        }
        return true
    }

    permutations((0..7).toList()).forEach { perm ->
        if (inputs.any { perm[it.row] != it.column } || !isValid(perm)) return@forEach
        
        val grid = Array(8) { CharArray(8) { '.' } }
        perm.forEachIndexed { index, i -> grid[index][i] = 'Q' }
        return println(grid.joinToString(System.lineSeparator()) { it.joinToString("") })
    }

    error("なんで？")
}

private fun permutations(src: List<Int>): List<List<Int>> {
    if (src.size == 1) return listOf(src)
    val perms = mutableListOf<List<Int>>()
    val insertElement = src[0]
    permutations(src.drop(1)).forEach { perm ->
        for (i in 0..perm.size) {
            val newPerm = perm.toMutableList()
            newPerm.add(i, insertElement)
            perms.add(newPerm.toList())
        }
    }
    return perms
}