首页 > 代码库 > QueenPuzzle-N皇后问题
QueenPuzzle-N皇后问题
详见-算法之美-p180.
#include <iostream> #include <memory.h> #include <conio.h> #include <stdlib.h> using namespace std; /* 92 solution. * * * * * * * Q * * * Q * * * * Q * * * * * * * * * Q * * * * * * * * * * Q * * * Q * * * * * * * * * * * * Q * * * * * Q * * * */ class QueenPuzzle { public: QueenPuzzle(int _n); public: void printOut(); void QueenDFS(int _n); int IsValidate(int _n); private: int sum; int max; int * queen; }; QueenPuzzle::QueenPuzzle(int _n) { this->sum = 0; this->max = _n; this->queen = new int[this->max](); } void QueenPuzzle::printOut() { for(int i = 0; i < this->max; i++) { for(int j = 0; j < this->max; j++) { if(j == this->queen[i]) cout << "Q "; else cout << "* "; } cout << endl; } cout << endl << "Enter any key to continue, Q key exit:" << endl << endl; if(getch() == ‘q‘) exit(0); } void QueenPuzzle::QueenDFS(int _n) { if(_n == this->max) { sum++; cout << endl << sum << " solution." << endl; this->printOut(); return; } for(int i = 0; i < this->max; i++) { this->queen[_n] = i; if(IsValidate(_n)) { this->QueenDFS(_n + 1); } } } int QueenPuzzle::IsValidate(int _n) { for(int i = 0; i < _n; i++) { if(this->queen[i] == this->queen[_n]) return 0; if(abs(this->queen[i] - this->queen[_n]) == (_n - i)) return 0; } return 1; } int main() { QueenPuzzle queen(8); queen.QueenDFS(0); return 0; }
QueenPuzzle-N皇后问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。