过河卒

Problem Description

棋盘上A点有一个过河卒,需要走到目标B点。卒行走的规则:可以向下、或者向右。同时在棋盘上的任一点有一个对方的马(如C点),该马所在的点和所有跳跃一步可达的点称为对方马的控制点(马走日字),卒不能通过对方马的控制点。棋盘用坐标表示,A点(0,0)、B点(n, m) (n,m为不超过20的整数),同样马的位置坐标是需要给出的,C≠A且C≠B。现在要求你计算出卒从A点能够到达B点的路径的条数。

Input

输入有多组数据,对于每组数据只有一行,分别为B的坐标n,m和马的坐标。

Output

对于每组输入,输出从A点能够到达B点的路径的条数。

Sample Input

8 6 0 4

Sample Output

1617

Author

HYNU



代码:
#include <cstdio>
#include <cstring>	
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	int n,m,nn,mm,i,j;
	long long f[100][100];
	while(cin>>n>>m>>nn>>mm)
	  {
      nn++; mm++; n++; m++;	
    	memset(f,0,sizeof(f)); f[0][1]=1;
     	for (i=1;i<=n;i++)
	      for (j=1;j<=m;j++)
	        if ((abs(i-nn)+abs(j-mm)==3)&&(i!=nn)&&(j!=mm)||(i==nn&&j==mm));
	        else f[i][j]=f[i-1][j]+f[i][j-1];	      
	    cout<<f[n][m]<<endl;
    }
	return 0;
}


过河问题中,棋盘上 A 点有一个过河,需要走到目标 B 点,行走规则是可以向下或者向右,同时棋盘上 C 点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点 [^2]。 ### 算法思路 可以使用动态规划来解决此问题。具体步骤如下: 1. **划分阶段**:按照在棋盘上的行进过程划分阶段,每到达一个新的格子就是一个新的阶段。 2. **定义状态**:设`dp[i][j]`表示到达第`i`行第`j`列格子的路径数量。 3. **状态转移方程**:由于只能向下或向右走,所以`dp[i][j] = dp[i - 1][j] + dp[i][j - 1]`(前提是该格子不是马的控制点)。 4. **初始条件**:`dp[0][0] = 1`,即初始在起点的路径数为 1。对于第一行和第一列,若没有马的控制点,路径数为 1,若遇到马的控制点,后续的路径数都为 0。 5. **最终结果**:`dp[m][n]`,其中`m`和`n`分别是目标点的行和列坐标。 ### 代码实现 ```python # 马的八个控制点偏移量 horse_offset = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] # 检查是否在棋盘内 def is_in_board(x, y, m, n): return 0 <= x <= m and 0 <= y <= n # 检查是否是马的控制点 def is_horse_control(x, y, horse_x, horse_y): if (x == horse_x and y == horse_y): return True for dx, dy in horse_offset: new_x, new_y = horse_x + dx, horse_y + dy if new_x == x and new_y == y: return True return False # 解决过河问题 def solve_horse_blocked_pawn(m, n, horse_x, horse_y): dp = [[0] * (n + 1) for _ in range(m + 1)] # 初始化起点 if not is_horse_control(0, 0, horse_x, horse_y): dp[0][0] = 1 # 初始化第一行 for j in range(1, n + 1): if not is_horse_control(0, j, horse_x, horse_y): dp[0][j] = dp[0][j - 1] # 初始化第一列 for i in range(1, m + 1): if not is_horse_control(i, 0, horse_x, horse_y): dp[i][0] = dp[i - 1][0] # 填充动态规划数组 for i in range(1, m + 1): for j in range(1, n + 1): if not is_horse_control(i, j, horse_x, horse_y): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m][n] # 示例使用 m, n = 3, 3 # 目标点坐标 horse_x, horse_y = 1, 1 # 马的坐标 result = solve_horse_blocked_pawn(m, n, horse_x, horse_y) print(result) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值