CODE[VS]1010 过河卒

本文介绍了一种解决过河卒问题的方法,通过递归搜索从起点到终点的所有可能路径,并排除受马控制点限制的路线。使用 C 语言实现了一个程序来计算从棋盘左上角到右下角的有效路径数量。

题目:http://codevs.cn/problem/1010/
思路:a(x,y)到b(n,m)的路径为ad(x+1, y)到b的路径与ar(x, y+1)到b的路径之和。
题解:

/* 1010 过河卒 */ 
#include <stdio.h>

#define MAXD 21                 /* 最大棋盘 */ 

int chessboard[MAXD][MAXD];     /* 棋盘 */ 
int n, m, x, y;                 /* 棋盘大小, C点坐标 */ 
int count;                      /* 路径计数 */ 

/* a to b路径查询 */ 
void a_to_b(int ax, int ay){
    /* 到达B点,路径计数加一 */ 
    if(ax == n && ay == m){
        count++;
    }
    else{
        /* 如果未到边界且右移一步不是马控制点,右移 */
        if(ay + 1 <= m){
            if(chessboard[ax][ay + 1] != 1){
                a_to_b(ax, ay + 1);
            }
        }
        /* 如果未到边界且下移一步不是马控制点,下移 */
        if(ax + 1 <= n){
            if(chessboard[ax + 1][ay] != 1){
                a_to_b(ax + 1, ay);
            }
        } 
    }
}

/* 主函数入口 */ 
int main(int argc, char *argv[]) {
    int xi, yi;     /* 索引 */

    /* 获取棋盘大小和C点坐标 */
    scanf("%d %d %d %d", &n, &m, &x, &y); 
    /* 初始化棋盘,将马控制点标记为1,其他为0 */ 
    for(xi = 0; xi <= n; xi++){
        for(yi = 0; yi <= m; yi++){
            chessboard[xi][yi] = 0;
        }
    }
    /* c */
    chessboard[x][y] = 1;
    /* p1 */
    if(x + 2 <= n && y + 1 <= m){
        chessboard[x + 2][y + 1] = 1;
    }
    /* p2 */
    if(x + 1 <= n && y + 2 <= m){
        chessboard[x + 1][y + 2] = 1;
    }
    /* p3 */
    if(x - 1 >= 0 && y + 2 <= m){
        chessboard[x - 1][y + 2] = 1;
    }
    /* p4 */
    if(x - 2 >= 0 && y + 1 >= 0){
        chessboard[x - 2][y + 1] = 1;
    }
    /* p5 */
    if(x - 2 >= 0 && y - 1 >= 0){
        chessboard[x - 2][y - 1] = 1;
    }
    /* p6 */
    if(x - 1 >= 0 && y - 2 >= 0){
        chessboard[x - 1][y - 2] = 1;
    }
    /* p7 */
    if(x + 1 <= n && y - 2 >= 0){
        chessboard[x + 1][y - 2] = 1;
    }
    /* p8 */
    if(x + 2 <= n && y - 1 >= 0){
        chessboard[x + 2][y - 1] = 1;
    }

    count = 0;
    a_to_b(0, 0);
    printf("%d", count);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值