问题:在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--;
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){
ways++;
return false;
}
steps--;
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;
}