zoukankan      html  css  js  c++  java
  • 中国马的跳法

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

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

    程序中,以左上角坐标为(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
    ", count);
        for(i=0; i<ps; i++) {
            printf("%2d: %d %d
    ", i+1, stackrow[i], stackcol[i]);
        }
        printf("
    ");
    
        getchar();
    }
    


  • 相关阅读:
    MSSQL_打开xp_cmdshell
    想在win7 32bit的情况下装个64位虚拟机的想法
    查看系统已运行了多久
    sql弄个表结构出来..
    在win下的cmd 的find
    告别google.com.hk的龟速
    VC常用数据类型使用转换详解
    C++中的文件输入/输出ios:xx eat Processing(zz)
    X86汇编语言学习手记(1)
    程序员数据结构笔记
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564959.html
Copyright © 2011-2022 走看看