八皇后问题C++代码
趁着刚刚考完试,把自己总结的一点东西分享一下。
#include<math.h>
#include<stdlib.h>
int t[]={2,5,3,1,7,0,0,0};
#include <iostream>
#include<vector>
using namespace std;
bool chess[8][8] = {
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
};
void Queen();
int main()
{
Queen();
vector<int> x;
vector<int> y;
for (int m = 0; m < 8; m++)
{
for (int n = 0; n < 8; n++)
{
if (chess[m][n])
{
x.push_back(m);
y.push_back(n);
}
}
}
if (x.size() != 8 || y.size() != 8)
{
cout << 0 << endl;
return 0;
}
for (int i = 0; i < x.size()-1; i++)
{
for (int j = i+1; j < x.size(); j++)
{
if (x[i] == x[j] || y[i] == y[j] || x[i] - x[j] == y[i] - y[j] || x[i] - x[j] == y[j] - y[i])
{
cout << 0 << endl;
return 0;
}
}
}
cout << 1 << endl;
return 0;
}
bool find(int a[8],int e)
{
for(int i=0;i<8;i++)
{
if(a[i]==e)
return true;
}
return false;
}
int Random(int a,int b)
{
return (rand()%(b-a)+a);//产生随机数
}
int Place(int x[],int k)//皇后k摆放在x[k]列
{
for(int i=0;i<k;i++)
{
if(x[i]==x[k]||abs(i-k)==abs(x[i]-x[k]))
return 1;
}
return 0;//不冲突
}
void Queen()
{
int i,j,count=0;
for(i=5;i<8;)
{
j=Random(0,8);
t[i]=j; //皇后i摆放在j列
if(Place(t,i)==0)
{
count++;
i++;
}
else if(count==8)
{
break;
}
}
for(i=0;i<8;i++)
{
int c=t[i];
chess[i][c]=1;
cout<<t[i]<<" ";
}
cout<<endl<<"___________________"<<endl;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
cout<<chess[i][j]<<" ";
cout<<endl;
}
}
运行结果如下:
由于使用的随机算法,有时候可能不能运行出正确答案,因此提前预置了5个数。如此一来,算法的效率明显提高了,同时也防止由于随机而产生的偏离使得算法运行效率低下。
欢迎大家提出意见,我们一起交流。