Poj3239 Solution to the n Queens Puzzle (n queen problem)
Solution to
NQueens Puzzle
Time Limit:1000 MS |
|
Memory Limit:131072 K |
Total Submissions:3494 |
|
Accepted:1285 |
|
Special Judge |
Description
The eight queens puzzle is the problem of putting eight chess queens on an 8 × 8 chessboard such that none of them is able to capture any other. The puzzle has been generalized to arbitraryN×NBoards. GivenN, You are to find a solution toNQueens puzzle.
Input
The input contains multiple test cases. Each test case consists of a single integerNBetween 8 and 300 (inclusive). A zero indicates the end of input.
Output
For each test case, output your solution on one line. The solution is a permutation of {1, 2 ,...,N}. The number inITh place meansITh-column queen in placed in the row with that number.
Sample Input
80
Sample Output
5 3 1 6 8 2 4 7
Solution:
1. When n mod 6! = 2 or n mod 6! = 3:
[,..., N], [,..., n-1] (n is an even number)
[,..., N-1], [,..., n] (n is an odd number)
2. When n mod 6 = 2 or n mod 6 = 3
(When n is an even number, k = n/2; when n is an odd number, k = (n-1)/2)
[K, k + 2, k + 4 ,..., n], [2, 4 ,..., k-2], [k + 3, k + 5 ,..., n-1], [1, 3, 5 ,..., k + 1] (k is an even number, n is an even number)
[K, k + 2, k + 4 ,..., n-1], [2, 4 ,..., k-2], [k + 3, k + 5 ,..., n-2], [, 5 ,..., k + 1], [n] (k is an even number, n is an odd number)
[K, k + 2, k + 4 ,..., n-1], [1, 3, 5 ,..., k-2], [k + 3 ,..., n], [2, 4 ,..., k + 1] (k is an odd number, n is an even number)
[K, k + 2, k + 4 ,..., n-2], [, 5 ,..., k-2], [k + 3 ,..., n-1], [2, 4 ,..., k + 1], [n] (k is an odd number, n is an odd number)
(There are six sequences above. One sequence in a row, and the brackets are added to help you identify the subsequence. The subsequence and the subsequence are in a continuous relationship. Ignore the brackets. The number of I is ai, indicating that there is a queen in the ai column of row I; In the sequence omitted by..., the numbers of adjacent two increase by 2 .)
Reference code:
# Include
# Include
Using namespace std; int main (int I) {int n; // Number of Queens while (cin> n) {if (! N) break; if (n % 6! = 2 & n % 6! = 3) {if (n % 2 = 0) // n is an even number {for (I = 2; I <= n; I + = 2) cout <