八皇后问题
问题:在8*8的国际象棋棋盘中放入八个皇后,任意两个皇后都不能互相吃掉,有多少种排法?
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
---|---|---|---|---|---|---|---|---|
0 | @ | |||||||
1 | @ | |||||||
2 | @ | |||||||
3 | @ | |||||||
4 | @ | |||||||
5 | @ | |||||||
6 | @ | |||||||
7 | @ |
上面的布局可以用序列 0 6 3 5 7 1 4 2来描述,第 i个数字表示在第 i行的相应位置有一个棋子,如下:
行号 :0 1 2 3 4 5 6 7
列号 :0 6 3 5 7 1 4 2
这只是皇后放置的一个解。编一个程序找出所有皇后放置的解。
并把它们以上面的序列方法输出,解按字典顺序排列。
输出全部解,最后一行是解的总个数。
1.代码完整表示:
#include<iostream>
#include<cmath>
using namespace std;
int a[8];
int ans=0;//统计有多少解
//在第0~t-1行已经确定了的情况下,
//穷举第t行和以后所有行的所有可能
//把满足条件的输出
void output()
{
int i;
ans++;
for(i = 0; i < 8; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
//判断棋盘(row,col)处是否能放皇后
//flag=1,能放
int canplace(int row, int col)
{
int i, flag;
flag = 1;
for(i = 0; i < row; i++)
{
//同列,45度方向的都不能放皇后
if(a[i] == col || row - i == abs(col - a[i]))
{
flag = 0;
break;
}
}
return(flag);
}
//递归求解,递归调用结束条件是t=8
void dfs(int t)
{
int i;
//
if(t == 8)
{
output();
}
else
{
for(i = 0; i < 8; i++)
{
if(canplace(t, i))
{
a[t] = i;
dfs(t + 1);
}
}
}
}
int main()
{
dfs(0);
cout<<ans<<endl;
}
2.拓展为N皇后问题,则只需要输入n,循环条件改为i<n,即可,打印出所有放置结果。代码如下:
#include<iostream>
#include<cmath>
using namespace std;
#define max 100
int n;
int a[max];
int cnt=0,ans=0;
//在第0~t-1行已经确定了的情况下,
//穷举第t行和以后所有行的所有可能
//把满足条件的输出
void output()
{
int i, j;
cnt++;ans++;
cout << cnt << " : " << endl;
for(i = 0; i < n; i++)
{
//cout << a[i];
//输出一行,在a[i]处输出'X',其余位置输出'.'
for(j = 0; j < n; j++)
{
if(j == a[i])
{
cout << 'X';
}
else
{
cout << '.';
}
}
cout << endl;
}
cout << endl;
}
int canplace(int row, int col)
{
int i, flag;
flag = 1;
for(i = 0; i < row; i++)
{
if(a[i] == col || row - i == abs(col - a[i]))
{
flag = 0;
break;
}
}
return(flag);
}
void dfs(int t)
{
int i;
if(t == n)
{
output();
}
else
{
for(i = 0; i < n; i++)
{
if(canplace(t, i))
{
a[t] = i;
dfs(t + 1);
}
}
}
}
int main()
{
cin>>n;
dfs(0);
cout<<ans<<endl;
}
上午上数据结构的时候王岐老师讲了一下这道题,中午的时候大类学院开线上会议讲解大二分专业的事情,触动很大,原来我马上就是一个大二党了。就想着写博客来记录自己学了些什么,也算是一种梳理。于是这就是我的第一篇。