版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mushao999/article/details/45341383
[问题描述]
:
如图,A 点有一个过河卒,需要走到目标 B 点。卒行走规则:可以向下、或者向右。同时在棋盘上的任一点有一个对方的马(如上图的C点),该马所在的点和所有跳跃一步可达的点称为对方马的控制点。例如上图 C 点上的马可以控制 9 个点(图中的P1,P2 … P8 和 C)。卒不能通过对方马的控制点。
棋盘用坐标表示,A 点(0,0)、B 点(n,m)(n,m 为不超过 20 的整数,并由键盘输入),同样马的位置坐标是需要给出的(约定: C<>A,同时C<>B)。现在要求你计算出卒从 A 点能够到达 B 点的路径的条数。
[输入]:
键盘输入
B点的坐标(n,m)以及对方马的坐标(X,Y){不用盘错}
[输出]:
屏幕输出
一个整数(路径的条数)。
[输入输出样例]:
输入:
6 6 3 2
输出:
17
解决问题的关键是找出递推公式f(x,y)=f(x-1,y)+f(x,y-1);
在实际做的过程中要提前标记马的控制点,在马的控制点出f(x,y)=0。
在边界上的点f(x,y)=1,但需要注意的问题是,一旦边界上一个点为马的控制点,则它后面的所有点的路径数均为0。
解决方案如下
import java.util.Scanner;
public class Main {
/**
* 程序入口
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
sc.close();
String[] strings1=s1.split(" ");
String[] strings2=s2.split(" ");
if(strings1.length<2||strings2.length<2)
{
return;
}
int bX=Integer.parseInt(strings1[0]);
int bY=Integer.parseInt(strings1[1]);
int horseX=Integer.parseInt(strings2[0]);
int horseY=Integer.parseInt(strings2[1]);
int[][] flag=new int[bX+1][bY+1];//标志矩阵
//先标记马的控制点
flag[horseX][horseY]=1;
if(horseX-1>=0)
{
if(horseY-2>=0)
{
flag[horseX-1][horseY-2]=1;
}
if(horseY+2<=bY)
{
flag[horseX-1][horseY+2]=1;
}
if(horseX-2>=0)
{
if(horseY-1>=0)
{
flag[horseX-2][horseY-1]=1;
}
if(horseY+1<=bY)
{
flag[horseX-2][horseY+1]=1;
}
}
}
if(horseX+1<=bX)
{
if(horseY-2>=0)
{
flag[horseX+1][horseY-2]=1;
}
if(horseY+2<=bY)
{
flag[horseX+1][horseY+2]=1;
}
if(horseX+2<=bX)
{
if(horseY-1>=0)
{
flag[horseX+2][horseY-1]=1;
}
if(horseY+1<=bY)
{
flag[horseX+2][horseY+1]=1;
}
}
}
int[][] result=new int[bX+1][bY+1]; //保存结果的矩阵
//先处理边界
boolean isBlocked=false;
for(int i=0;i<=bX;i++)
{
if(flag[i][0]==1||isBlocked)
{
flag[i][0]=0;
isBlocked=true;
}
else {
result[i][0]=1;
}
}
isBlocked=false;
for(int i=0;i<=bY;i++)
{
if(flag[0][i]==1||isBlocked)
{
result[0][i]=0;
isBlocked=true;
}
else {
result[0][i]=1;
}
}
for(int i=1;i<=bX;i++)
{
for(int j=1;j<=bY;j++)
{
if(flag[i][j]==1)
{
result[i][j]=0;
}
else {
result[i][j]=result[i-1][j]+result[i][j-1];
}
}
}
System.out.println(result[bX][bY]);
}
}///:~