码迷,mamicode.com
首页 > 其他好文 > 详细

N皇后问题2

时间:2015-08-03 18:18:23      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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 sequence 2 4 6 1 3 5, which gives the column positions of the checkers for each row from 技术分享 to 技术分享:

ROW    1    2   3   4   5   6
COLUMN 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 of 技术分享). Print the solutions using the column notation described above. Print the 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

 

题意:N皇后问题,需要输出前三种排放和可以排放的方式的数量

解题思路:只需要记数输出三次,其他的和N皇后一样......(这里用二维数组来判断是否同列同斜线...防超时)

 

 

代码如下:

 

 

 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     else
16     {
17         for(int i=1; i<=n; i++)
18         {
19            if(!vis[0][i]&&!vis[1][cur+i]&&!vis[2][cur-i+n])   //判断是否和前面的皇后冲突
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 }

 

N皇后问题2

标签:

原文地址:http://www.cnblogs.com/huangguodong/p/4699689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!