题目链接:过河卒
初始条件: f(0,1) = f(1,0) =1
关系式:f(i,j) = f(i-1,j) + f(i,j-1)
java代码:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n,m,a,b;
Scanner in = new Scanner(System.in);
// 坐标加2,可以避免:在标记不能走的位置时发生数组越界的情况
// 简单来说就是让左边和上边空出来两层不使用
n = in.nextInt()+2;
m = in.nextInt()+2;
a = in.nextInt()+2;
b = in.nextInt()+2;
// 初始化数组
long arr1[][] = new long[n+1][m+1];
boolean arr2[][] = new boolean[n+1][m+1];
for(int i=0;i<=n;++i) {
Arrays.fill(arr1[i], 0);
Arrays.fill(arr2[i], true);
}
// 标记不能走的位置
arr2[a][b] = false;
arr2[a-1][b-2] = false;
arr2[a-2][b-1] = false;
arr2[a-2][b+1] = false;
arr2[a-1][b+2] = false;
arr2[a+1][b-2] = false;
arr2[a+2][b-1] = false;
arr2[a+1][b+2] = false;
arr2[a+2][b+1] = false;
// 开始递推计算
arr1[2][2] = 1;
for(int i=2;i<=n;++i) {
for(int j=2;j<=m;++j) {
if(i==2&&j==2) continue;
if(arr2[i][j]!=false)
arr1[i][j] = arr1[i-1][j]+arr1[i][j-1];
}
}
System.out.println(arr1[n][m]);
}
}