题目描述
棋盘上 AA 点有一个过河卒,需要走到目标 BB 点。卒行走的规则:可以向下、或者向右。同时在棋盘上 CC 点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦过河卒”。
棋盘用坐标表示,AA 点 (0, 0)(0,0)、BB 点 (n, m)(n,m),同样马的位置坐标是需要给出的。
![noip2002 过河卒 (动态规划求路径总数)_#include](https://s2.51cto.com/images/blog/202209/26142600_633145f877fbc5122.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=/resize,m_fixed,w_1184)
现在要求你计算出卒从 AA 点能够到达 BB 点的路径的条数,假设马的位置是固定不动的,并不是卒走一步马走一步。
输入格式
一行四个正整数,分别表示 BB 点坐标和马的坐标。
输出格式
一个整数,表示所有的路径条数。
输入输出样例
输入
输出
说明/提示
对于 100 \%100% 的数据,1 \le n, m \le 201≤n,m≤20,0 \le0≤ 马的坐标 \le 20≤20。
题目地址:
洛谷1002
解法1:动态规划
dp[i,j] 代表走到位置(i, j)的方案有多少种
dp[0, 0] = 1
dp[i, j] = dp[i, j - 1] + dp[i, j - 1]
#include<cstdio>
#include<algorithm>
using namespace std;
long long f[20+5][20+5];
int n, m, horse_x, horse_y;
bool ok(int x, int y) {
if (x > n || y > m) return 0;
if (x == horse_x && y == horse_y) return 0;
if (abs(horse_x - x) == 1 && abs(horse_y - y) == 2) return 0;
if (abs(horse_x - x) == 2 && abs(horse_y - y) == 1) return 0;
return 1;
}
int main() {
scanf("%d%d%d%d", &n, &m, &horse_x, &horse_y);
f[0][0] = 1;
for(int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++) {
if (ok(i, j)) {
if (j) f[i][j] += f[i][j - 1];
if (i) f[i][j] += f[i - 1][j];
}
}
printf("%I64d\n",f[n][m]);
return 0;
}
解法2:动态规划
在解法1的基础上,优化空间效率
dp[0] = 1
dp[i] = dp[i] + dp[i - 1]
#include<cstdio>
#include<algorithm>
using namespace std;
long long f[20+5];
int n, m, horse_x, horse_y;
bool ok(int x, int y) {
if (x < 0 || x > n || y < 0 || y > m) return 0;
if (x == horse_x && y == horse_y) return 0;
if (abs(horse_x - x) == 1 && abs(horse_y - y) == 2) return 0;
if (abs(horse_x - x) == 2 && abs(horse_y - y) == 1) return 0;
return 1;
}
int main() {
scanf("%d%d%d%d", &n, &m, &horse_x, &horse_y);
f[0] = 1;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (!ok(i, j)) {
f[j] = 0;
continue;
}
if(j) f[j] += f[j - 1];
}
}
printf("%I64d\n",f[m]);
return 0;
}
解法三:矩阵乘法、直接数学排列公式计算
https://www.luogu.com.cn/blog/yummy-loves-114514/solution-p1002