N queen Question 2, n queen
Description
Examine the checkerboard below and note that the six checkers are arranged on the board so that one and only one is placed in each row and each column, and there is never more than one in any diagonal. (Diagonals run from southeast to northwest and southwest to northeast and include all diagonals, not just the major two .)
1 2 3 4 5 6 -------------------------1 | | O | | | | | -------------------------2 | | | | O | | | -------------------------3 | | | | | | O | -------------------------4 | O | | | | | | -------------------------5 | | | O | | | | -------------------------6 | | | | | O | | -------------------------
The solution shown above is described by the sequence2 4 6 1 3 5
, Which gives the column positions of the checkers for each row from:
ROW 1 2 3 4 5 6COLUMN 2 4 6 1 3 5
This is one solution to the checker challenge. write a program that finds all unique solution sequences to the Checker Challenge (with ever growing values ). print the solutions using the column notation described above. print the first three solutions in numerical order, as if the checker positions form the digits of a large number, and then a line with the total number of solutions.
Input
A single line that contains a single integer () that is the dimension of the checkerboard.
Output
The first three lines show the first three solutions found, presented as numbers with a single space between them. The fourth line shows the total number of solutions found.
Sample Input
6
Sample Output
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
Question: N queen's question, we need to output the number of the first three emission and emission-permitted methods.
Solution: you only need to output three records. The others are the same as the N queen... (Here we use a two-dimensional array to determine whether the same column is the same as the diagonal line... anti-timeout)
The Code is as follows:
1 # include <stdio. h> 2 int n, t = 0, vis [25] [25], c [13]; 3 void dfs (int cur) 4 {5 if (cur = n + 1) 6 {7 t ++; 8 if (t <4) 9 {10 for (int I = 1; I <= n-1; I ++) 11 printf ("% d", c [I]); 12 printf ("% d \ n", c [n]); 13} 14} 15 else16 {17 for (int I = 1; I <= n; I ++) 18 {19 if (! Vis [0] [I] &! Vis [1] [cur + I] &! Vis [2] [cur-I + n]) // determine whether it is in conflict with the Queen. 20 {21 c [cur] = I; 22 vis [0] [I] = vis [1] [cur + I] = vis [2] [cur-I + n] = 1; 23 dfs (cur + 1 ); 24 vis [0] [I] = vis [1] [cur + I] = vis [2] [cur-I + n] = 0; 25} 26} 27} 28} 29 int main () 30 {31 scanf ("% d", & n); 32 dfs (1 ); 33 printf ("% d \ n", t); 34 return 0; 35}