国产探花免费观看_亚洲丰满少妇自慰呻吟_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;// 沒有可遍歷的路線 }*/}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宽城| 通江县| 西藏| 松滋市| 阳春市| 长白| 凉山| 股票| 崇仁县| 米泉市| 屯门区| 思南县| 巴青县| 神池县| 安陆市| 开化县| 广德县| 兴安县| 锡林浩特市| 衡阳市| 武义县| 鲁甸县| 武强县| 都昌县| 视频| 武宁县| 天柱县| 古浪县| 图木舒克市| 巴彦淖尔市| 蕉岭县| 乳山市| 松溪县| 西乌珠穆沁旗| 和顺县| 济源市| 临澧县| 凯里市| 马关县| 维西| 华池县|