八皇后问题的递归算法和非递归算法实现

最近我研究了一下八皇后的问题,分别用递归算法和非递归算法实现了问题求解过程。在此,分享给大家,希望提出你的意见。

// EightQueens.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<Windows.h>
using namespace std;

#define N_QUEENS 8

int total = 0;
int xPos[ N_QUEENS + 1 ] = { 0 };

bool IsPosOk ( int k, int j, int *x )
{
    if( k <= 0 || k >N_QUEENS || j <= 0 || j >N_QUEENS || x == nullptr )
    {
        return false;
    }

    for( int i = 1; i < k; i++ )
    {
        if( ( j == x[i] ) || ( abs( k - i ) == abs( j - x[i] ) ) )
        {
            return false;
        }
    }

    return true;
}

void Iterate( void )
{
    int k = 1;
    int next = 1;

    while( k >0 )
    {
        int j = 1;

        for( j = next; j <= N_QUEENS; j++ )
        {
            if( IsPosOk( k, j, xPos ) == true )
            {
                xPos[k] = j;
                break;
            }
        }

        if( j <= N_QUEENS )
        {
            if( k == N_QUEENS )
            {
                for( int i = 1; i <= N_QUEENS; i++ )
                {
                    cout<<" "<<xPos[i];
                }

                cout<<endl;
                total++;
                next = j + 1;
            }
            else
            {
                k++;
                xPos[k] = 0;
                next = 1;
            }
        }
        else
        {
            xPos[k] = 0;
            k--;
            next = xPos[k] + 1;
        }
    }
}

void BackTrace( int k )
{
    for( int j = 1; j <= N_QUEENS; ++j )
    {
        if( IsPosOk( k, j, xPos ) == true )
        {
            xPos[k] = j;

            if( k == N_QUEENS )
            {
                total++;

                for( int i = 1; i <= N_QUEENS; i++ )
                {
                    cout<<" "<<xPos[i];
                }

                cout<<endl;
                return;
            }
            else
            {
                BackTrace( k + 1 );
            }
        }

        xPos[k] = 0;
    }
}

int main( void )
{
    cout<<"Eight Queens' Solutions are:"<<endl;
    int iTick = GetTickCount();
    BackTrace( 1 );
    cout<<"Total Solution1 is "<<total<<endl;
    cout<<"Solution1 Elapse : "<<GetTickCount() - iTick<<endl;
    total = 0;
    iTick = GetTickCount();
    Iterate();
    cout<<"Total Solution2 is "<<total<<endl;
    cout<<"Solution2 Elapse : "<<GetTickCount() - iTick<<endl;

    getchar();
    return 0;
}

递归算法比较容易理解,在非递归算法中,需要特别注意next的用法,它用来记录下一次迭代的起点。非递归算法的本质就是使用栈结构来实现递归,从程序执行效率上来看,非递归算法略高于递归算法。

    原文作者:递归算法
    原文地址: https://blog.csdn.net/feihongchen/article/details/46553487
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞