马拦过河卒
Time Limit: 3000 ms
Memory Limit: 65536 KiB
Problem Description
棋盘上A点有一个过河卒,需要走到目标B点。卒行走的规则:可以向下、或者向右。同时在棋盘上C点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦过河卒”。棋盘用坐标表示,A点(0,0)、B点(n,m)(n,m为不超过15的整数),同样马的位置坐标是需要给出的。现在要求你计算出卒从A点能够到达B点的路径的条数,假设马的位置是固定不动的,并不是卒走一步马走一步。
Input
一行四个数据,用空格分隔,分别表示B点的坐标和马的坐标。
Output
一个数据,表示所有的路径条数。
Sample Input
6 6 3 3
Sample Output
6
Hint
Source
马位于(2,2)时,任何结果都为0
import java.util.*;
public class Main {
final static int horse[][] = { { -1, -2 }, { 1, -2 }, { 2, -1 }, { 2, 1 }, { 1, 2 }, { -1, 2 }, { -2, 1 },
{ -2, -1 }, { 0, 0 } };//必须包含马的位置
static int Map[][] = new int[22][22], x1 = 0, y1 = 0, sum = 0;//sum记录路径数量
static int Move[][] = { { 1, 0 }, { 0, 1 } };
static int judge(int x, int y) { //判断数组下标是否越界
if (x >= 0 && y >= 0 && x <= 15 && y <= 15)
return 1;
else
return 0;
}
static void DFS(int x, int y) {
for (int i = 0; i < 2; i++) { //表示向下或向右移动,当数据未越过数组下标且该点未被马掌控,则可以将当前点的位置移到该点
if (judge(x + Move[i][0], y + Move[i][1]) == 1 && Map[x + Move[i][0]][y + Move[i][1]] == 0) {
x += Move[i][0];
y += Move[i][1];
if (x == x1 && y == y1)
sum++;
else
DFS(x, y);//未到达目标处则继续递归
x -= Move[i][0];//回溯
y -= Move[i][1];
}
}
}
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
x1 = cin.nextInt();
y1 = cin.nextInt();
int x2 = cin.nextInt();
int y2 = cin.nextInt();
for (int i = 0; i < 9; i++) {
if (judge(x2 + horse[i][0], y2 + horse[i][1]) == 1)
Map[x2 + horse[i][0]][y2 + horse[i][1]] = 1;
}
DFS(0, 0);
System.out.println(sum);
cin.close();
}
}<span style="font-family:'Microsoft YaHei';color:#999999;"><span style="background-color:rgb(255,255,255);">
</span></span>
package leslie1;//step[n][m]=step[n-1][m]+step[n][m-1],注意:我们关注的是路径条数而这跟具体怎么走这条路径无关;
import java.util.*;
public class Main {
final static int horse[][] = { { -1, -2 }, { 1, -2 }, { 2, -1 }, { 2, 1 }, { 1, 2 }, { -1, 2 }, { -2, 1 },
{ -2, -1 }, { 0, 0 } };// 必须包含马的位置
static int Map[][] = new int[22][22], x1 = 0, y1 = 0;// Map标记点是否能走(为0时能走)
static int Move[][] = { { 1, 0 }, { 0, 1 } };
static int step[][] = new int[22][22];// 记录到x2,y2的路径数量
static int judge(int x, int y) {// 判断数组下标是否越界
if (x >= 0 && y >= 0 && x <= 15 && y <= 15)
return 1;
else
return 0;
}
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
x1 = cin.nextInt();
y1 = cin.nextInt();
int x2 = cin.nextInt();
int y2 = cin.nextInt();
for (int i = 0; i < 9; i++) {
if (judge(x2 + horse[i][0], y2 + horse[i][1]) == 1)
Map[x2 + horse[i][0]][y2 + horse[i][1]] = 1;
}
step[0][0] = 1;
for (int i = 1; i <= x1; i++) {
if (Map[i][0] == 0)
step[i][0] = step[i - 1][0];
}
for (int i = 1; i <= y1; i++) {
if (Map[0][i] == 0)
step[0][i] = step[0][i - 1];
}
for (int i = 1; i <= x1; i++)
for (int j = 1; j <= y1; j++)
if (Map[i][j] == 0)
step[i][j] = step[i - 1][j] + step[i][j - 1];
System.out.println(step[x1][y1]);
cin.close();
}
}