Description
The great mathematician Gauss once proposed a difficult problem in chess:
Eight queens.
The Queen of chess can move vertically, horizontally, and diagonally, but how can eight queens be placed on an eight-by-eight-square-lattice board, so that any queen will not be attacked by any other queen, that is, two queens will not be in the same row, in the same column or on the same diagonal line. How many types of such placement are there?
Of course, it is no longer difficult to have the eight queens problem like computers. We have to deal with Queen n!
That is to say, on the N * n Board, there are several ways to place n Queens so that they do not attack each other.
Input
The first row is the number of test data groups T, and the following row contains t, each row has an integer N (0 <n <11)
Output
Number of Placement Solutions
Sample input 2
1
4 sample output 1
2
Solution:
This seems to be a classic question, but more classic is the post-8 question. How many methods are there? I remember using backtracing.
The same algorithm is used for calculation. You can create a function that is used to determine whether each method meets the meaning of the question, and then use another function to enumerate all situations. This is almost the case.
# Include <stdio. h> # include <math. h> # include <string. h> int N;/* */static int Total = 0; void output (int * A) {int I; ++ total;} int can (INT D, int * a, int * Mk) {int I; If (MK [A [d]) return 0; for (I = 0; I <D; I ++) if (ABS (A [I]-A [d]) = ABS (I-d) return 0; return 1;} void Qu (INT D, int *, int * Mk) {int I, j; If (D> = N) output (a); elsefor (I = 0; I <n; I ++) {A [d] = I; If (CAN (D, A, MK) {MK [I] = 1; qu (D + 1, A, MK ); MK [I] = 0 ;}}int main () {int A [100], MK [100] = {0}; int number; scanf ("% d ", & number); While (number --) {Total = 0; scanf ("% d", & N); memset (A, 0, sizeof ()); memset (MK, 0, sizeof (MK); qu (0, A, MK); printf ("% d \ n", total);} return 0 ;}