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

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

// 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的用法,它用来记录下一次迭代的起点。非递归算法的本质就是使用栈结构来实现递归,从程序执行效率上来看,非递归算法略高于递归算法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值