八皇后问题的解法

  1. 暴力搜索
#include 

using namespace std;

int judge(int a[])
{
     for (int i = 2; i <=8 ; ++i)
     {
        for (int j = 1; j <=i -1; ++j)
        {
            if ((a[i]==a[j])||((a[i]-a[j])==(i-j))||((a[i]-a[j])==(j-i)))
                return 0;
            else
                continue;
        }
     }
     return 1;
}
int a[9] ;
int search()
{
    int count =0;
        for (a[1] = 1; a[1]<=8; ++a[1])
    {

        for (a[2] = 1; a[2] <=8; ++a[2])
    {

        for (a[3] = 1; a[3] <=8; ++a[3])
    {

        for (a[4] = 1; a[4] <=8; ++a[4])
    {

        for (a[5] = 1; a[5] <=8; ++a[5])
    {

        for (a[6] = 1; a[6] <=8; ++a[6])
    {

        for (a[7] = 1; a[7] <=8; ++a[7])
    {

        for (a[8] = 1; a[8] <=8; ++a[8])
    {

        if(judge(a) ==1)
            count++;        
    }
    }
    }
    }
    }
    }       
    }
    }
    return count;
}

int main(int argc, char const *argv[])
{
    int count;
    count =search();
    cout<<count<return 0;
}

结果:八皇后问题的解法_第1张图片

2 回溯
循环一次调用一次judge()函数,不行就回头;
八皇后问题的解法_第2张图片

3 回溯+递归

#include 

using namespace std;

int k =1;
int num =8;
int count =1;
int a[9] ={0};

int judge(int k)
{
    for (int i = 2; i <= k; ++i)
    {
        for (int j = 1; j <= i-1 ; ++j)
        {
            if((a[i]==a[j])||((a[i]-a[j])==(i-j))||((a[i]-a[j])==(j-i)))
                return 0;
            else 
                continue;
        }
    }
    return 1;   
}

int search(int k)
{
    if(k > num)
    {
        cout<<"Way"<":";
        count ++;
        for(int n=0;n <=num; n ++)
        {
            cout<""<else
        {
            for (int i = 1; i <= 8; ++i)
            {
                a[k] =i;
                if(!judge(k))
                    continue;
                else
                    search(k+1);
            }

        }

    return 0;   
}

int main(int argc, char const *argv[])
{
    search(1);
    return 0;
}

八皇后问题的解法_第3张图片

n个皇后:

#include 

using namespace std;

int k =1;
int num;
int count =1;

int judge(int k,int *a)
{
    for (int i = 2; i <= k; ++i)
    {
        for (int j = 1; j <= i-1 ; ++j)
        {
            if((a[i]==a[j])||((a[i]-a[j])==(i-j))||((a[i]-a[j])==(j-i)))
                return 0;
            else 
                continue;
        }
    }
    return 1;   
}

int search(int k,int *a)
{
    if(k > num)
    {
        cout<<"Way"<":";
        count ++;
        for(int n=0;n <=num; n ++)
        {
            cout<""<else
        {
            for (int i = 1; i <= 8; ++i)
            {
                a[k] =i;
                if(!judge(k,a))
                    continue;
                else
                    search(k+1,a);
            }

        }

    return 0;   
}

int main(int argc, char const *argv[])
{   
    cin>>num;
    int *a =new int[num+1];
    for (int i = 0; i <= num; ++i)
    {
        a[i] =0;
    }   
    search(1,a);
    delete []a;
    return 0;
}

你可能感兴趣的:(数据结构和算法)