【c++】求解八皇后問題

爲:在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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章