为:在8×8格的国际象棋上摆放8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。一共92个解
解决思路:一层层回溯,采用深度优先的递归算法。
动态分配的数组不方便调试,看不到数据,用Position[]这种数组好调试,clsArr为了能使用vector封装了下数组,实现了索引重载。
Position 是从 (1,1)开始,代表第一行第一列。
 
算法源码:头文件

#pragma once
#include"Position.h"
#include<vector>
#include<array>
using std::array;
using std::vector;

class QueenGame
{
private:
const int SIZE = 9;
int getCount;
int count;
Position* posArr;
clsArr pA;
vector<clsArr>vecResult;
bool PosIsOK(int x, int y);
public:
QueenGame(int n = 8) {
count = n;
getCount = 0;
posArr = new Position[count];
}
~QueenGame() {
delete[]posArr;
}
QueenGame(const QueenGame& q) {
this->count = q.count;
this->getCount = q.getCount;
this->posArr = new Position[q.count];
for (size_t i = 0; i < q.count; i++)
{
this->posArr[i] = q.posArr[i];
}
}
const vector<clsArr> GetResult()const {
return vecResult;
}
void Play(int x, int y);
};

View Code

定义:
#include "QueenGame.h"
#include"Position.h"
#include<math.h>
bool QueenGame::PosIsOK(int x, int y) {

for (size_t i = 0; i < count; i++)
{
Position pos = pA[i];

if (pos.x <= 0 && pos.y <= 0) {
continue;
}
if (x == pos.x || y == pos.y) {
return false;
}
else {
if (std::abs((x - pos.x) * 1.0 / (y - pos.y)) == 1) {
return false;
}
}
}
return true;
}
void QueenGame::Play(int x, int y) {
if (x >= SIZE && y >= SIZE) {
return;
}
for (; y < SIZE; y++)
{
if (PosIsOK(x, y)) {
Position pos(x, y);

*(posArr + (getCount)) = pos;
pA[getCount] = pos;
++getCount;
if (x < SIZE - 1) {
Play(x + 1, 1);
}
else {
int sss = 0;
if (getCount == count) {
vecResult.push_back(pA);
pA[--getCount].set(-1, -1);

continue;
}

}
}
}
if (getCount >= 0)
{
--getCount;
posArr[getCount].set(-1, -1);
pA[getCount].set(-1, -1);
}
return;
}

运行:

QueenGame qGame(8);
    qGame.Play(1,1);
    auto result= qGame.GetResult();

辅助类:

struct Position
{
 int x;
 int y;

 Position(int a, int b) {
 x = a;
 y = b;
 }
 Position() {
 x = -1;
 y = -1;
 }
 void set(int a, int b) {
 x = a;
 y = b;
 }
};
class clsArr {
public:
Position pos[8];
Position& operator[](int i) {
return pos[i];
}
};

View Code