N皇后问题2
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 <stdio.h>
int n,t=,vis[][],c[];
void dfs(int cur)
{
if(cur==n+)
{
t++;
if(t<)
{
for(int i=; i<=n-; i++)
printf("%d ",c[i]);
printf("%d\n",c[n]);
}
}
else
{
for(int i=; i<=n; i++)
{
if(!vis[][i]&&!vis[][cur+i]&&!vis[][cur-i+n]) //判断是否和前面的皇后冲突
{
c[cur]=i;
vis[][i]=vis[][cur+i]=vis[][cur-i+n]=;
dfs(cur+);
vis[][i]=vis[][cur+i]=vis[][cur-i+n]=;
}
}
}
}
int main()
{
scanf("%d",&n);
dfs();
printf("%d\n",t);
return ;
}
最新文章
- 【PostgreSQL】PostgreSQL的安装
- Tomcat编码配置解疑
- SpeechLib 语音播报
- css margin
- mysql常用函数汇总
- 下一代大数据系统和4S标准
- [HIve - LanguageManual] Joins
- iOS 滑动页面标题切换颜色渐变效果
- Office远程代码执行漏洞CVE-2017-0199复现
- CentOS服务器上的 git 包版本控制
- CF 1042F
- mysql理论结合实际篇(一)
- ToString()格式和用法大全,C#实现保留两位小数的方法
- java利用EasyPoi实现Excel导出功能
- hdu 4960 数列合并
- 将string str中的str转换成字符数组
- Git7:使用Gitlab管理远程仓库
- Eureka 客户端 配置Eureka 爬坑
- 进入docker的4种方式
- spider-抓取网页内容