设为首页 加入收藏

TOP

poj3239 Solution to the n Queens Puzzle (n皇后问题)
2015-07-20 17:19:50 来源: 作者: 【 】 浏览:3
Tags:poj3239 Solution the Queens Puzzle 皇后 问题

Solution to the n Queens Puzzle
Time Limit: 1000MS Memory Limit: 131072K
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 arbitrary n × n boards. Given n, you are to find a solution to the n queens puzzle.

\

Input

The input contains multiple test cases. Each test case consists of a single integer n between 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 in the ith place means the ith-column queen in placed in the row with that number.

Sample Input

8
0

Sample Output

5 3 1 6 8 2 4 7

解题思路:

一、当n mod 6 != 2 或 n mod 6 != 3时:


[2,4,6,8,...,n],[1,3,5,7,...,n-1] (n为偶数)


[2,4,6,8,...,n-1],[1,3,5,7,...,n ] (n为奇数)

二、当n mod 6 == 2 或 n mod 6 == 3时


(当n为偶数,k=n/2;当n为奇数,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为偶数,n为偶数)

[k,k+2,k+4,...,n-1],[2,4,...,k-2],[k+3,k+5,...,n-2],[1,3,5,...,k+1],[n] (k为偶数,n为奇数)

[k,k+2,k+4,...,n-1],[1,3,5,...,k-2],[k+3,...,n],[2,4,...,k+1] (k为奇数,n为偶数)

[k,k+2,k+4,...,n-2],[1,3,5,...,k-2],[k+3,...,n-1],[2,4,...,k+1],[n ] (k为奇数,n为奇数)

(上面有六条序列。一行一个序列,中括号是我额外加上的,方便大家辨认子序列,子序列与子序列之间是连续关系,无视中括号就可以了。第i个数为ai,表示在第i行ai列放一个皇后;... 省略的序列中,相邻两数以2递增。)

参考代码:

#include
  
   
#include
   
     using namespace std; int main(int i) { int n; //皇后数 while(cin>>n) { if(!n) break; if(n%6!=2 && n%6!=3) { if(n%2==0) //n为偶数 { for(i=2;i<=n;i+=2) cout<
    
     


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++ Redis mset 二进制数据接口封.. 下一篇hdu 2602 01背包

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·【C语言】动态内存管 (2025-12-27 06:23:20)
·C语言中的内存管理 - (2025-12-27 06:23:16)
·C语言指南:C语言内 (2025-12-27 06:23:14)
·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)