|
发表于 2016-7-4 17:35:04
|
显示全部楼层
- #include<iostream>
- #include<cmath>
- using namespace std;
- const int N=8;
- static int count=0;//定义静态(static)变量来表示是第几个方案。
- int Queen[N+1][N+1]={0};
- bool isLegal(int i,int j){
- //判断在i行,j列的位置是否可以满足条件。
- for(int m=1;m<=i-1;m++){
- int n=Queen[m][0];
- if(n==j || abs(j-n)==abs(i-m))//对角相减的绝对值相等。
- return false;
- }
- return true;
- }
- void print(){
- //作为一个打印函数
- count++;
- cout<<"第"<<count<<"种放法"<<endl;
- for(int i=1;i<=N;i++){
- for(int j=1;j<=N;j++){
- cout<<Queen[i][j]<<" ";
- }
- cout<<endl;
- }
- cout<<endl;
- }
- void eightQueen(int i){//八皇后核心代码
- if(i>N)print();//判断结束条件
- else{
- for(int j=1;j<=N;j++){
- Queen[i][j]=1;
- if(isLegal(i,j)){
- Queen[i][0]=j;
- eightQueen(i+1);
- }
- Queen[i][j]=0;
- }
- }
- }
- int main()
- {
- eightQueen(1);
- return 0;
- }
复制代码 |
|