您的位置:首页 > 其它

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

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

// 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的用法,它用来记录下一次迭代的起点。非递归算法的本质就是使用栈结构来实现递归,从程序执行效率上来看,非递归算法略高于递归算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息