过河卒问题(java实现)
题目描述
输入格式
一行四个正整数,分别表示B点坐标和马的坐标
输出格式
表示所有路径条数的一个整数
输入输出样例
输入:6 6 3 3
输出:6
注:对于100%的数据,1 <= n,m <= 20,0 <= 马的坐标 <= 20
代码(象棋里的马走到日字形的对角)
import java.util.Scanner;
public class GuoHeZu{
static Scanner cin = new Scanner(System.in);
static int n = cin.nextInt();
static int m = cin.nextInt();//棋盘大小
static int x = cin.nextInt();
static int y = cin.nextInt();//马的坐标
static int a[][] = new int[n+1][m+1]; //存放马的位置及它可以到达的地方
static long b[][] = new long[n+1][m+1];//存放路线
public static void main(String args[]) {
if(x>=2) {
a[x-2][y+1] = -1;
if(y>0) {
a[x-2][y-1] = -1;
}
}
if(y>=2) {
a[x+1][y-2] = -1;
if(x>0) {
a[x-1][y-2] = -1;
}
}
if(y>0) {
a[x+2][y-1] = -1;
}
if(x>0) {
a[x-1][y+2] = -1;
}
a[x][y] = -1;
a[x+1][y+2] = -1;
a[x+2][y+1] = -1;//以上操作把马所有可达的地方都赋-1
b[0][0] = 1;
for(int i=0;i<=n;i++) {
for(int j=0;j<=m;j++) {
if(i>0 && j>0) {
b[i][j] = b[i-1][j]+b[i][j-1];
}
if(i==0 && j>0)
b[i][j]=b[i][j-1];//防止越界
if(j==0 && i>0)
b[i][j]=b[i-1][j];//防止数组越界
if(a[i][j] == -1) {
b[i][j] = 0;
}
}
}
System.out.println(b[n][m]);
}
}