回溯法解决N皇后问题
/*
* Queue.h
*
* Created on: 2010-4-1
* Author: root
*/
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
#ifndef QUEEN_H_
#define QUEEN_H_
class Queen {
public:
Queen();
Queen(int n);
void printResult();
virtual ~Queen();
private:
int num;
vector<vector<int> > resultVector;
int * a;
bool isTrue(int i);
void getResult(int i);
};
#endif /* QUEUE_H_ */
* Queue.h
*
* Created on: 2010-4-1
* Author: root
*/
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
#ifndef QUEEN_H_
#define QUEEN_H_
class Queen {
public:
Queen();
Queen(int n);
void printResult();
virtual ~Queen();
private:
int num;
vector<vector<int> > resultVector;
int * a;
bool isTrue(int i);
void getResult(int i);
};
#endif /* QUEUE_H_ */
/*
* Queue.cpp
*
* Created on: 2010-4-1
* Author: root
*/
#include "Queen.h"
Queen::Queen() {
// TODO Auto-generated constructor stub
}
Queen::Queen(int n)
{
num = n;
a = new int[n+1];
}
Queen::~Queen() {
// TODO Auto-generated destructor stub
delete [] a;
}
bool Queen::isTrue(int i)
{
for(int j=1;j<i;j++)
{
if(abs(a[i]-a[j])==abs(i-j)||a[i]==a[j])
return false;
}
return true;
}
void Queen::getResult(int i)
{
if(i>num)
{
vector<int> v;
for(int j=1;j<=num;j++)
{
v.push_back(a[j]);
}
resultVector.push_back(v);
}
else
{
for(int j=1;j<=num;j++)
{
a[i]=j;
if(isTrue(i))
getResult(i+1);
}
}
}
void Queen::printResult()
{
getResult(1);
for(vector<vector<int> >::iterator it = resultVector.begin();it!=resultVector.end();it++)
{
for(vector<int>::iterator subIt = it->begin();subIt!=it->end();subIt++)
{
for(int i=1;i<=num;i++)
{
if(i==*subIt)
{
cout<<"1 ";
}
else
{
cout<<"0 ";
}
}
cout<<endl;
}
cout<<"---------------------------------------"<<endl;
}
}
* Queue.cpp
*
* Created on: 2010-4-1
* Author: root
*/
#include "Queen.h"
Queen::Queen() {
// TODO Auto-generated constructor stub
}
Queen::Queen(int n)
{
num = n;
a = new int[n+1];
}
Queen::~Queen() {
// TODO Auto-generated destructor stub
delete [] a;
}
bool Queen::isTrue(int i)
{
for(int j=1;j<i;j++)
{
if(abs(a[i]-a[j])==abs(i-j)||a[i]==a[j])
return false;
}
return true;
}
void Queen::getResult(int i)
{
if(i>num)
{
vector<int> v;
for(int j=1;j<=num;j++)
{
v.push_back(a[j]);
}
resultVector.push_back(v);
}
else
{
for(int j=1;j<=num;j++)
{
a[i]=j;
if(isTrue(i))
getResult(i+1);
}
}
}
void Queen::printResult()
{
getResult(1);
for(vector<vector<int> >::iterator it = resultVector.begin();it!=resultVector.end();it++)
{
for(vector<int>::iterator subIt = it->begin();subIt!=it->end();subIt++)
{
for(int i=1;i<=num;i++)
{
if(i==*subIt)
{
cout<<"1 ";
}
else
{
cout<<"0 ";
}
}
cout<<endl;
}
cout<<"---------------------------------------"<<endl;
}
}