
洛谷 P1002
过河卒
题目
棋盘上 AA 点有一个过河卒,需要走到目标 BB 点。卒行走的规则:可以向下、或者向右。同时在棋盘上 CC 点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦过河卒”。
棋盘用坐标表示,AA 点(0, 0)(0,0)、BB 点(n, m)(n,m)(nn, mm 为不超过 2020 的整数),同样马的位置坐标是需要给出的。

现在要求你计算出卒从 AA 点能够到达 BB 点的路径的条数,假设马的位置是固定不动的,并不是卒走一步马走一步。
思路
害,太久没做题了,说实话一开始对这一筹莫展,想着可能会用递归,之后看了题解终于才懂了要使用递推来做。
答案
参考代码
代码
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
//记录马的位置以及马控制的位置
int[][] array1 = new int[x1 + 1][y1 + 1];
long[][] array2 = new long[x1 + 1][y1 + 1];
array1[x2][y2] = -1;
for (int i = 0; i <= x1; i++) {
for (int j = 0; j <= y1; j++) {
if ((Math.abs((i - x2)) == 1 && Math.abs((j - y2)) == 2) || Math.abs((i - x2)) == 2 && Math.abs((j - y2)) == 1) {
array1[i][j] = -1;
}
}
}
//递推
for (int i = 0; i <= x1; i++) {
for (int j = 0; j <= y1; j++) {
if (array1[i][j] != -1) {
if (i == 0 && j == 0) {
array2[i][j] = 1;
}
if (i > 0 && j > 0) {
array2[i][j] = array2[i - 1][j] + array2[i][j - 1];
}
if (i == 0 && j > 0) {
array2[i][j] = array2[i][j - 1];
}
if (j == 0 && i > 0) {
array2[i][j] = array2[i - 1][j];
}
} else {
array2[i][j] = 0;
}
}
}
System.out.println(array2[x1][y1]);
}
}
原文博客地址:https://noahcode.cn/