P1796 求解马走棋问题

这篇博客探讨了如何计算在一个给定大小的棋盘上,马按照特定规则从左下角走到右上角的不同路径数量。通过递归算法实现,适合初学者理解马的走法及其路径计数技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

在 m 行 n 列的棋盘上有一个中国象棋中的马,马走日字且只能向右走。

请找到可行路径的条数,使得马从棋盘的左下角(1,1) 走到右上角 (m,n)。

Tip 1: 本题为单组输入。

Tip 2: 马向右走指从 (X,Y) 走到 (X+2, Y+1) 或 (X+1, Y+2) 位置

输入描述

一行,两个正整数 n m。

输出描述

一行,表示相应的路径条数。

样例输入

Copy to Clipboard
4 4 

样例输出

Copy to Clipboard
2

/*
 * @Description: To iterate is human, to recurse divine.
 * @Autor: Recursion
 * @Date: 2022-04-25 14:28:18
 * @LastEditTime: 2022-04-25 14:43:05
 */
#include <bits/stdc++.h>
#define LL long long 
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 501;
int n,m,x,y,ans;
int a[N][N];
bool vis[N][N];

const int dx[2]={1,2};
const int dy[2]={2,1};
 
queue<pair<int,int> > q;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> n >> m;
    memset(a,0,sizeof(a));
    memset(vis,false,sizeof(vis));
    a[1][1] = 0;
    vis[1][1] = 1;
    q.push(make_pair(1,1));
    while(!q.empty()){
        int xx = q.front().first;
        int yy = q.front().second;
        q.pop();
        for(int i = 0;i < 2;i++){
            int tx = xx + dx[i];
            int ty = yy + dy[i];
            if(tx>0&&tx<=n&&ty>0&&ty<=m){
                if(tx == n&&ty==m){
                    ans++;
                    continue;
                }
                q.push(make_pair(tx,ty));
            }
        }
    }

    cout << ans << endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值