1310 n queen issues

Source: Internet
Author: User
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 ;}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.