八皇后问题求解1

#include <iostream.h>
using namespace std;
int col[8],Left[15],Right[15];
int queen[8];
int n=0;
int sum=0;

void generate()
{
        int h,i;
        for(h=0;h<=7;h++)
        {
                if(col[h]&& Left[n+h] && Right[n-h+7])
                {
                        queen[n]=h;
                        col[h]=false;
                        Left[n+h]=false;
                        Right[n-h+7]=false;
                        n+=1;
                        if(n==8)
                        {
                                sum++;
                                cout<<"  "<<sum;
                                for(i=0;i<=7;i++)
                                cout<<"/t"<<queen[i];
                                cout<<endl;
                        }
                        else generate();
                        n--;
                        Left[n+h]=true;
                        Right[n-h+7]=true;
                        col[h]=true;
                }
        }
}
int  main()
{
        int c,s;
        for(c=0;c<=7;++c)
                col[c]=true;
        for(s=0;s<=14;++s)
        {
                Left[s]=true;
                Right[s]=true;

        }

        cout<<"    行数/t0/t1/t2/t3/t4/t5/t6/t7"<<endl;

        generate();

        cout<<"八皇后摆法总数:"<<sum<<endl;

        return 0;

}

Left[]用来判断左对角线能否放皇后

Right[]....

h列号

n为行号

 

 

 

 

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int n=8;
int x[8]={0};
int sum=0;

int place(int k)
{
 int j;
 for(j=0;j<k;j++)
  if((fabs(k-j)==fabs(x[j]-x[k]))||(x[j]==x[k])) return 0;
 return 1;
}

void backtrace(int t)
{
 int i;
 if(t>=n)
 {
  putchar('/n');
  for(i=0;i<n;i++)
   printf("%d/t",x[i]);
  sum++;
  if(!(sum%25)) getchar();
 }
 else
  for(i=0;i<n;i++)
  {
   x[t]=i;
   if(place(t)) backtrace(t+1);
  }
}

void main()
{
 backtrace(0);
 printf("%d/n",sum);
 getchar();
}

你可能感兴趣的:(八皇后问题求解1)