問題:在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;// 沒有可遍歷的路線 }*/}