標籤:
1 //核心代碼如下 2 //Queen--放置皇后 3 4 #include "queue.h" 5 6 queue::queue() 7 { 8 const int maxn = 9*9; 9 this->QN = 4; 10 this->board = new bool[maxn]; 11 for (int i = 0; i < maxn; i++) { 12 this->board[i] = false; 13 } 14 this->judgeRecursion = true; 15 this->count = 0; 16 } 17 18 queue::queue(int N) 19 { 20 const int maxn = 81; 21 if (N > 9 || N < 4) 22 this->QN = 4; //如果不合法就正規化棋盤 23 else 24 this->QN = N; 25 this->board = new bool[maxn]; 26 for (int i = 0; i < maxn; ++i) //初始化棋盤,未放置棋子的棋盤設定為false 27 this->board[i] = false; 28 this->judgeRecursion = true; 29 this->count = 0; 30 } 31 32 bool queue::available (const int Crow, const int Ccol) const //當前行,當前列 33 { 34 for (int hor = 0; hor < Crow; ++hor) { 35 //縱向尋找 36 if (board[hor * QN + Ccol]) //已經放置皇后的棋盤處為true 37 return false; //則返回false--放置不合法 38 } 39 int obli = Crow, oblj = Ccol; 40 while (obli > 0 && oblj > 0) { 41 if (board[(--obli) * QN + (--oblj)]) 42 return false; //左斜上尋找 43 } 44 obli = Crow, oblj = Ccol; 45 while (obli > 0 && oblj < QN - 1) { 46 if (board[(--obli) * QN + (++oblj)]) 47 return false; //右斜上尋找 48 } 49 return true; //都沒有,則該位置可以放置皇后 50 } 51 52 //列印棋盤 53 void queue::show (bool *Q) 54 { 55 const int maxn = 81; 56 for (int i = 0; i < maxn; i++) 57 Q[i] = this->board[i]; 58 } 59 60 //重新初始化棋盤 61 void queue::reset () 62 { 63 const int maxn = 81; 64 for (int i = 0; i < maxn; i++) 65 this->board[i] = false; 66 this->judgeRecursion = true; 67 this->count = 0; 68 } 69 70 void queue::reset (int N) 71 { 72 const int maxn = 81; 73 if (N < 4 || N > 9) this->QN = 4; 74 else 75 this->QN = N; 76 77 for (int i = 0; i < maxn; i++) 78 this->board[i] = false; 79 this->judgeRecursion = true; 80 this->count = 0; 81 } 82 83 queue::~queue () 84 { 85 delete []board; 86 board = nullptr; 87 } 88 89 /** 90 * @brief queue::answer --- 放置皇后 91 * @param solu --- 求解的方法數 92 * @param Crow --- 當前的行數 93 * @param Q --- 棋盤,用來列印 94 */ 95 void queue::answer (int solu, int cur, bool *Q) 96 { 97 if (!judgeRecursion) //遞迴結束,中斷 98 return; 99 if (cur == QN) { //當前行到最後一行,則一種方案結束100 count++;101 if (count == solu) { //遞迴到第solu方案時停止102 this->show (Q);103 judgeRecursion = false; //停止遞迴104 return;105 }106 return;107 }108 else109 {110 for (int col = 0; col < QN; col++)111 {112 if (available (cur, col)) //檢查當前行,列113 {114 board[cur * QN + col] = true; //合法則放置皇后115 answer (solu, cur + 1, Q); //遞迴下一行116 //如果回溯法中使用了輔助的全域變數,則一定要及時把它們恢複原狀.117 //特別的,若函數有多個出口,則需在每個出口處恢複被修改的值118 board[cur * QN + col] = false;119 }120 }121 }122 }
原始碼: 連結: https://pan.baidu.com/s/1slOrCJV 密碼: 6xtn
Qt_介面程式實現_N皇后問題_Q_Queen