中国马的跳法

问题:中国象棋的半张棋盘上,马从左下角跳到右上角,总共有几种跳法。

求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。

程序中,以左上角坐标为(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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值