国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

騎士巡游問題

2019-11-08 18:30:34
字體:
來源:轉載
供稿:網友

問題:在N行N列的棋盤上,一位騎士按象棋中“馬走日”的走法從初始坐標位置(SX, SY)出發,要求遍歷(巡游)棋盤中每一個位置一次。請輸出其實巡游的位置順序,或輸出無解。

解答:這是一道典型的遞歸算法題,詳見代碼

代碼:

#include <iostream>using namespace std;// 棋盤邊長、起始位置、總步數const int N = 5, SI = 0, SJ = 0, STEPS = N*N - 1;int map[N][N];// 棋盤數組,存儲遍歷序號static int ways;// 遍歷的方法數bool move(int si, int sj, int steps){ if (si < 0 || si > N - 1 || sj<0 || sj>N - 1){ return false;// 越界 } if (map[si][sj] != 0){ return false;// 已被訪問過 } if (steps == 0){ return true;// 成功遍歷一次 } steps--;// 剩余步數-1 map[si][sj] = STEPS - steps;// 存儲遍歷序號 // 八個位置逐一嘗試是否可行,直至全部不可行 if (move(si + 1, sj + 2, steps) == true)return true; if (move(si + 1, sj - 2, steps) == true)return true; if (move(si - 1, sj + 2, steps) == true)return true; if (move(si - 1, sj - 2, steps) == true)return true; if (move(si + 2, sj + 1, steps) == true)return true; if (move(si + 2, sj - 1, steps) == true)return true; if (move(si - 2, sj + 1, steps) == true)return true; if (move(si - 2, sj - 1, steps) == true)return true; map[si][sj] = 0;// 全部不可行,往后退一步,這一步不能存下來 return false;// 表明此路不通}void main(){ if (move(SI, SJ, STEPS) == true){ for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ cout.fill('0');// 設置填充字符 cout.width(2);// 設置域寬 cout << map[i][j] << " ";// 輸出遍歷序號 } cout << endl; } } else{ cout << "No path found!" << endl;// 沒有可遍歷的路線 }}

額外內容:若需輸出遍歷的方法數,需要這么改

#include <iostream>using namespace std;// 棋盤邊長、起始位置、總步數const int N = 5, SI = 0, SJ = 0, STEPS = N*N - 1;int map[N][N];// 棋盤數組,存儲遍歷序號static int ways;// 遍歷的方法數bool move(int si, int sj, int steps){ if (si < 0 || si > N - 1 || sj<0 || sj>N - 1){ return false;// 越界 } if (map[si][sj] != 0){ return false;// 已被訪問過 } if (steps == 0){ //return true;// 成功遍歷一次 ways++;// 遍歷方法+1種 return false;// 假裝遍歷失敗以尋找新的遍歷路線 } steps--;// 剩余步數-1 map[si][sj] = STEPS - steps;// 存儲遍歷序號 // 八個位置逐一嘗試是否可行,直至全部不可行 if (move(si + 1, sj + 2, steps) == true)return true; if (move(si + 1, sj - 2, steps) == true)return true; if (move(si - 1, sj + 2, steps) == true)return true; if (move(si - 1, sj - 2, steps) == true)return true; if (move(si + 2, sj + 1, steps) == true)return true; if (move(si + 2, sj - 1, steps) == true)return true; if (move(si - 2, sj + 1, steps) == true)return true; if (move(si - 2, sj - 1, steps) == true)return true; map[si][sj] = 0;// 全部不可行,往后退一步,這一步不能存下來 return false;// 表明此路不通}void main(){ move(SI, SJ, STEPS);// 遍歷 cout << ways << endl;// 輸出方法數 /*if (move(SI, SJ, STEPS) == true){ for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ cout.fill('0');// 設置填充字符 cout.width(2);// 設置域寬 cout << map[i][j] << " ";// 輸出遍歷序號 } cout << endl; } } else{ cout << "No path found!" << endl;// 沒有可遍歷的路線 }*/}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黎平县| 衢州市| 桃园市| 云龙县| 荆门市| 达尔| 卢湾区| 靖州| 明溪县| 安化县| 眉山市| 洛扎县| 黄山市| 锦州市| 北京市| 和田县| 连平县| 商都县| 那坡县| 大洼县| 大英县| 井陉县| 临邑县| 定结县| 谢通门县| 江都市| 汝阳县| 开鲁县| 肥乡县| 镇沅| 天全县| 民权县| 讷河市| 喀喇| 济阳县| 洛川县| 阿坝县| 清远市| 清远市| 霍邱县| 鄂尔多斯市|