#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); };
#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]; } };