递归:

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

int que[8]={0},cc=0;
void print()
{
    cc++;
    cout<<cc<<':';
    for(int i=0;i<=7;i++)
        cout<<que[i]<<' ';
    cout<<endl;
}
int check(int c)
{
    if(que[c]>8)return 0;
    for(int i=0;i<c;i++)
    {
        if(que[i]==que[c]||que[i]-que[c]==i-c||que[i]-que[c]==c-i)return 0;
    }
    return 1;
}

void queue8(int i)
{
    if(i==8){print();return;}
    for(int j=1;j<=8;j++)
    {
        que[i]=j;
        if(check(i))queue8(i+1);
    }
}

int main()
{
    queue8(0);
}

 

 

 

迭代:

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

int que[8]={0},c,count;
void print()
{
    c++;
    cout<<c<<':';
    for(int i=0;i<=7;i++)
        cout<<que[i]<<' ';
    cout<<endl;
}
int check(int c)
{
    if(que[c]>8)return 0;
    for(int i=0;i<c;i++)
    {
        if(que[i]==que[c]||que[i]-que[c]==i-c||que[i]-que[c]==c-i)return 0;
    }
    return 1;
}

void queue8()
{
    int cc=0;
    while(count>=0&&count<=7)
    {
        que[count]++;
        if(check(count))
        {
            count++;
        }
        else if(que[count]>8)que[count]=0,count--;
        if(count>7){print();count--;}
    }
}

int main()
{
    queue8();
}