问题:在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;// 没有可遍历的路线 }*/}