a*算法实现八数码问题java代码
时间: 2024-04-23 08:18:36 浏览: 145
Java-A*算法解决八数码问题算法源码
5星 · 资源好评率100%
以下是A*算法实现八数码问题的Java代码:
```
import java.util.*;
public class EightPuzzleSolver {
private static final int[][] GOAL = {{1, 2, 3}, {8, 0, 4}, {7, 6, 5}};
private static final int[][][] DISTANCE = new int[9][3][3];
static {
for (int num = 1; num <= 8; num++) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
DISTANCE[num][i][j] = Math.abs(i - (num - 1) / 3) + Math.abs(j - (num - 1) % 3);
}
}
}
}
private static class State implements Comparable<State> {
int[][] board;
int g;
int h;
State prev;
State(int[][] board, int g, State prev) {
this.board = board;
this.g = g;
this.h = calculateH(board);
this.prev = prev;
}
int f() {
return g + h;
}
@Override
public int compareTo(State o) {
return Integer.compare(f(), o.f());
}
boolean isGoal() {
return Arrays.deepEquals(board,
阅读全文