题目描述 Description
如图,A 点有一个过河卒,需要走到目标 B 点。卒行走规则:可以向下、或者向右。同时在棋盘上的任一点有一个对方的马(如上图的C点),该马所在的点和所有跳跃一步可达的点称为对方马的控制点。例如上图 C 点上的马可以控制 9 个点(图中的P1,P2 … P8 和 C)。卒不能通过对方马的控制点。
棋盘用坐标表示,A 点(0,0)、B 点(n,m)(n,m 为不超过 20 的整数,并由键盘输入),同样马的位置坐标是需要给出的(约定: C不等于A,同时C不等于B)。现在要求你计算出卒从 A 点能够到达 B 点的路径的条数。
1<=n,m<=15
输入描述 Input Description
键盘输入
B点的坐标(n,m)以及对方马的坐标(X,Y){不用判错}
输出描述 Output Description
屏幕输出
一个整数(路径的条数)。
样例输入 Sample Input
6 6 3 2
样例输出 Sample Output
17
数据范围及提示 Data Size & Hint
如描述
分析:
DFS,通过移动判断不在马的攻击范围即可,一直到达目标点B,假设马的位置坐标为(x,y),则马的其他八个可攻击范围的坐标分别为:(x+1,y-2), (x+1,y+2),(x+2,y-1),(x+2,y+1),(x-1,y-2),(x-1,y+2),(x-2,y-1)(x-2,y+1)。
代码如下:
public class DFSTest {
private static Integer ans = 0;
//马可攻击范围点
private static final Integer[][] horseXY = {{0,0},{1,-2},{1,2},{2,-1},{2,1},{-1,-2},{-1,2},{-2,-1},{-2,1}};
//targetXY[0][0],targetXY[0][1]目标点B坐标,targetXY[1][0],targetXY[1][1]马C坐标
private static final Integer[][] targetXY = new Integer[2][2];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入B和C坐标:");
String[] strs = scanner.nextLine().trim().split(" ");
targetXY[0][0] = Integer.parseInt(strs[0]);
targetXY[0][1] = Integer.parseInt(strs[1]);
targetXY[1][0] = Integer.parseInt(strs[2]);
targetXY[1][1] = Integer.parseInt(strs[3]);
DFSSearch(0,0);
System.out.println(ans);
}
private static void DFSSearch(int x, int y){
//到达目标B点
if (x == targetXY[0][0] && y == targetXY[0][1]){
ans++;
return;
}
//超出坐标范围
if(x < 0 || x > targetXY[0][0] || y < 0 || y > targetXY[0][1]){
return;
}
//马C点的可攻击点
for (int i = 0; i < 9; i++){
int hx = targetXY[1][0] + horseXY[i][0];
int hy = targetXY[1][1] + horseXY[i][1];
if (x == hx && y == hy){
return;
}
}
DFSSearch(x+1, y);
DFSSearch(x, y+1);
}
}