洛谷p1002过河卒java动态规划
时间: 2023-11-17 18:01:47 浏览: 185
动态规划java版本
4星 · 用户满意度95%
洛谷p1002过河卒是一道动态规划问题,题目要求在一个棋盘上,卒从起点出发,不能经过马的控制点,到达终点的所有路径数。以下是Java实现的动态规划解法:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
int[][] horse = new int[22][22];
int[][] dp = new int[22][22];
horse[x1][y1] = 1;
dp[x1][y1] = 1;
if (x1 - 1 >= 0 && y1 - 2 >= 0) horse[x1 - 1][y1 - 2] = 1;
if (x1 - 2 >= 0 && y1 - 1 >= 0) horse[x1 - 2][y1 - 1] = 1;
if (x1 - 2 >= 0 && y1 + 1 <= 20) horse[x1 - 2][y1 + 1] = 1;
if (x1 - 1 >= 0 && y1 + 2 <= 20) horse[x1 - 1][y1 + 2] = 1;
if (x1 + 1 <= 20 && y1 + 2 <= 20) horse[x1 + 1][y1 + 2] = 1;
if (x1 + 2 <= 20 && y1 + 1 <= 20) horse[x1 + 2][y1 + 1] = 1;
if (x1 + 2 <= 20 && y1 - 1 >= 0) horse[x1 + 2][y1 - 1] = 1;
if (x1 + 1 <= 20 && y1 - 2 >= 0) horse[x1 + 1][y1 - 2] = 1;
for (int i = x1 + 1; i <= x2; i++) {
for (int j = y1; j <= y2; j++) {
if (horse[i][j] == 0) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
System.out.println(dp[x2][y2]);
}
}
```
阅读全文