国际马的跳法

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

这个问题与中国象棋的棋盘上的跳马问题完全相同,只是起始和终止坐标的不同。但是,可以比较一下所有跳法的数量,了解问题复杂度的差异。

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

程序中,以左上角坐标为(0,0),马从左上角(0,0)跳到右下角(7,7)。

马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。

为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。

总共有18种跳法。与中国象棋半张棋盘上37种跳法相比,可以说中国象棋问题的复杂度更高。

/*
 *
 * 问题描述:国际象棋的棋盘上,一匹马从左上角跳到右下角,只允许往右跳,
 * 给出各种跳法。
 *
 * 国际象棋跳马问题算法程序
 *
 */

#include <stdio.h>

#define STACK_SIZE 100

struct stack {
    int row;
    int col;
} stack[STACK_SIZE];

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(0, 0);

    return 0;
}

void horse(int row, int col) {
    push(row, col);
    if(row == 7 && col == 7)
        output_result();
    if(row < 0 || row > 7 || col > 7) {
        ;
    } 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) {
    stack[ps].row = row;
    stack[ps].col = col;
    ps++;
}

void pop() {
    ps--;
}

void output_result() {
    count++;


    int i;
    printf("result %d
", count);
    for(i=0; i<ps; i++) {
        printf("%2d: %d %d
", i+1, stack[i].row, stack[i].col);
    }
    printf("
");

    getchar();
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564956.html