diff --git "a/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" "b/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" index 8ad3264433..d3aa8a114a 100644 --- "a/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" +++ "b/problems/kamacoder/0126.\351\252\221\345\243\253\347\232\204\346\224\273\345\207\273astar.md" @@ -335,6 +335,86 @@ IDA * 算法 对这一空间增长问题进行了优化,关于 IDA * 算法, ### Java +```java +import java.util.PriorityQueue; +import java.util.Scanner; + +class Knight implements Comparable { + 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 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 @@ -683,4 +763,3 @@ int main() { -