N皇后问题

#include <IOSTREAM.H>
#include <MATH.H>
#define LENGTH 8
int num=0;
int SuccessInsert(int (*a)[LENGTH],int x,int y)
{
    for (int i=0;i<LENGTH;i++)
    {
        for (int j=0;j<LENGTH;j++)
        {
            if (a[i][j]==1&&(i==x||j==y||abs(x-i)==abs(y-j)))
                return 0;
        }
    }
    a[x][y]=1;
    return 1;
}
void print(int (*a)[LENGTH])
{
    for (int i=0;i<LENGTH;i++)
    {
        for (int j=0;j<LENGTH;j++)
        {
            cout<<a[i][j]<<"  ";
        }
        cout<<endl;
    }
    cout<<++num<<endl;
}
void Back(int (*a)[LENGTH],int x,int count)
{
    if(count==LENGTH)
    {
        print(a);return;
    }
    for (int j=0;j<LENGTH;j++)
    {
        for (int k=0;k<LENGTH;k++)
            a[x][k]=0;
        if (SuccessInsert(a,x,j))
        {
            Back(a,x+1,count+1);
        }
    }
    for (int k=0;k<LENGTH;k++)
            a[x][k]=0;
}
int main()
{
    int a[LENGTH][LENGTH]={0};
    Back(a,0,0);
    cout<<num<<endl;
    print(a);
    return 0;
}
原文地址:https://www.cnblogs.com/GoAhead/p/2717240.html