// programme1.cpp : Defines the entry point for the console application.
//Author: C.J
// Date: 2013.4.26
#include "stdafx.h"
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
typedef struct cc{
int row;
int coloumn;
}loc;
void N_queen1(int *locate,int n,int N)
{//N皇后问题——回溯算法,递归解法
static int count=0;
if (n==N)
{ count++;
cout<<count<<"******************************"<<endl;
for (int i=0;i<N;i++)
{
cout<<i<<"行,"<<locate[i]<<"列"<<endl;
}
return;
}
int state=0;
for (int j=0;j<N;j++)
{
for(int z=0;z<n;z++)
{
if ((locate[z]==j)||((n-z)==abs(locate[z]-j)))
{
state=1;
break;
}
}
if (!state)
{
locate[n]=j;
N_queen1(locate,n+1,N);
}
state=0;
}
}
void N_queen2(int *locate,int N){
//回溯,非递归版本
int state1=0,count=0,state2=0;
stack<loc>st;
loc temp;
temp.row=0;
temp.coloumn=0;
int row=0;
int column=0;
for(int j=0;j<N;j++)
{
for(int z=0;z<row;z++)
{
if ((locate[z]==j)||((row-z)==abs(locate[z]-j)))
{
state1=1;
break;
}
}
if (!state1)
{
locate[row]=j;
if (row==N-1)
{
state2=1;
count++;
cout<<count<<"***************************"<<endl;
for(int i=0;i<N;i++)
cout<<"第"<<i<<"行,"<<locate[i]<<"列"<<endl;
}
temp.row=row;
temp.coloumn=j;
st.push(temp);
row++;
j=-1;
}
if (state1&&(j==N-1)||state2)
{
if(st.empty())break;
for(temp=st.top();(temp.coloumn==N-1)&&(!st.empty());temp=st.top())
{
st.pop();
if (st.empty())
{
j=N;
break;
}
}
if(!st.empty())st.pop();
j=temp.coloumn;
row=temp.row;
state2=0;
}
state1=0;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n=13;
int *locate=(int*)malloc(sizeof(int)*n);
memset(locate,0,sizeof(int)*n);
N_queen2(locate,n);
return 0;
}