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

import java.util.Arrays;
import java.util.Scanner;


public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in); 

		r = new int[8];
		Arrays.fill(r, -1);
		int k = sc.nextInt();
		for (int i = 0; i < k; i++) {
			r[sc.nextInt()] = sc.nextInt();
		}
		
		used = new boolean[8];
		perm = new int[8];
		permutation(0, 8);
		
    	String[] q = {"Q.......", ".Q......", "..Q.....", "...Q....", "....Q...", ".....Q..", "......Q.", ".......Q"};
    	for (int i = 0; i < 8; i++) {
    		System.out.println(q[res[i]]);
    	}
    	
        sc.close();
	}

	static int[] r;
	static int[] res;
	static boolean[] used;
	static int[] perm;

	// {0, 1, 2, 3, ...., n - 1}???????????????n!?????????????????????
	static void permutation(int pos, int n) {
		if (pos == n) {
			// perm[] ??????????????????
			for (int i = 0; i < n; i++) {
				if (r[i] != -1 && r[i] != perm[i]) {
					return;
				}
			}

			if (res == null) {
				// check
				boolean flag = true;
				for (int i = 0; i < n; i++) {
					for (int j = i + 1; j < n; j++) {
						if (perm[i] < n - (j - i) && perm[j] == perm[i] + j - i) {
							flag = false;
							break;
						}
						if (perm[i] >= j - i && perm[j] == perm[i] - (j - i)) {
							flag = false;
							break;
						}
					}
				}
				if (flag) {
					res = perm.clone();
				}
			}
			
			return;
		}
		// perm[]???pos?????????0???n-1?????????????????????????????????
		for (int i = 0; i < n; i++) {
			if (!used[i]) {
				perm[pos] = i;
				// i????????£????????§????????°???true
				used[i] = true;
				permutation(pos + 1, n);
				// ?????£????????????????????°?????????
				used[i] = false;
			}
		}
		
		return;
	}
}