2015 HUAS Summer Contest#2~B

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的矩阵,然后放东西且不能在同行同列及同斜线。利用回溯的方法可以解决(当把问题分成若干步骤并递归求解时,如果当前步骤没有合法选择,则函数将返回上一级递归调用)但是要注意标记了的数组要改回来,利用二维数组更好判断。

程序代码:

#include<cstdio>
int c[1000],vis[100][100];
int n,tot,t;
void search(int cur)
{
	if(cur==n+1) 
	{
		t++;
		if(t<=3)
		{
			for(int i=1;i<n;i++)
				printf("%d ",c[i]);
			printf("%d\n",c[n]);
			
		}
		tot++;
	}
	else for(int i=1;i<=n ;i++)
	{
		if(!vis[1][i]&&!vis[2][cur+i]&&!vis[3][cur-i+n])
		{
			c[cur]=i;
			vis[1][i]=vis[2][cur+i]=vis[3][cur-i+n]=1;
			search(cur+1);
			vis[1][i]=vis[2][cur+i]=vis[3][cur-i+n]=0;
		}
	}
}
int main()
{
	scanf("%d",&n);
	search(1);
	printf("%d\n",tot);
	return 0;
}
posted @ 2015-07-31 19:14  简约。  阅读(124)  评论(0编辑  收藏  举报