0126.骑士的攻击astar.md添加Java版本

This commit is contained in:
‘windscape’
2025-03-10 20:32:41 +08:00
parent e5b75dfd16
commit 1378685575

View File

@@ -335,6 +335,86 @@ IDA * 算法 对这一空间增长问题进行了优化,关于 IDA * 算法,
### Java ### Java
```java
import java.util.PriorityQueue;
import java.util.Scanner;
class Knight implements Comparable<Knight> {
int x, y;
int g, h, f;
public Knight(int x, int y, int g, int h, int f) {
this.x = x;
this.y = y;
this.g = g;
this.h = h;
this.f = f;
}
@Override
public int compareTo(Knight k) {
return Integer.compare(this.f, k.f);
}
}
public class Main {
static int[][] moves = new int[1001][1001];
static int[][] dir = { {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2} };
static int b1, b2;
static int Heuristic(Knight k) {
return (k.x - b1) * (k.x - b1) + (k.y - b2) * (k.y - b2);
}
static void astar(Knight k) {
PriorityQueue<Knight> que = new PriorityQueue<>();
que.add(k);
while (!que.isEmpty()) {
Knight cur = que.poll();
if (cur.x == b1 && cur.y == b2) {
break;
}
for (int i = 0; i < 8; i++) {
int nextX = cur.x + dir[i][0];
int nextY = cur.y + dir[i][1];
if (nextX < 1 || nextX > 1000 || nextY < 1 || nextY > 1000) {
continue;
}
if (moves[nextX][nextY] == 0) {
moves[nextX][nextY] = moves[cur.x][cur.y] + 1;
Knight next = new Knight(nextX, nextY, cur.g + 5, Heuristic(new Knight(nextX, nextY, 0, 0, 0)), 0);
next.f = next.g + next.h;
que.add(next);
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while (n-- > 0) {
int a1 = scanner.nextInt();
int a2 = scanner.nextInt();
b1 = scanner.nextInt();
b2 = scanner.nextInt();
for (int i = 0; i < 1001; i++) {
for (int j = 0; j < 1001; j++) {
moves[i][j] = 0;
}
}
Knight start = new Knight(a1, a2, 0, Heuristic(new Knight(a1, a2, 0, 0, 0)), 0);
start.f = start.g + start.h;
astar(start);
System.out.println(moves[b1][b2]);
}
scanner.close();
}
}
```
### Python ### Python
```Python ```Python
@@ -683,4 +763,3 @@ int main() {