N皇后问题——回溯算法

// 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值