问题:中国象棋的半张棋盘上,马从左下角跳到右上角,总共有几种跳法。
求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。
程序中,以左上角坐标为(0,0),马从左下角(4,0)跳到右上角(0,8)。
马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。
为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。
总共有37种跳法。
/*
*
* 问题描述:在半张中国象棋的棋盘上,一匹马从左下角跳到右上角,只允许往右跳,
* 给出各种跳法。
*
* 跳马问题算法程序
*
*/
#include <stdio.h>
int stackrow[100];
int stackcol[100];
int ps = 0;
int count = 0;
void horse(int row, int col);
void push(int row, int col);
void pop();
void output_result();
int main(void)
{
horse(4, 0);
return 0;
}
/* 函数功能:当前马调到row行col列
*
* 参数:row--行,col--列
*/
void horse(int row, int col) {
push(row, col);
if(row == 0 && col == 8)
output_result();
if(row < 0 || row > 4 || col > 8) {
;
} else {
horse(row - 2, col + 1);
horse(row - 1, col + 2);
horse(row + 1, col + 2);
horse(row + 2, col + 1);
}
pop();
}
void push(int row, int col) {
stackrow[ps] = row;
stackcol[ps] = col;
ps++;
}
void pop() {
ps--;
}
void output_result() {
count++;
int i;
printf("result %d\n", count);
for(i=0; i<ps; i++) {
printf("%2d: %d %d\n", i+1, stackrow[i], stackcol[i]);
}
printf("\n");
getchar();
}