用java代码写一个基于A* 算法的demo
时间: 2023-02-21 20:17:18 浏览: 102
A*算法demo
下面是一个使用 Java 语言实现的基于 A* 算法的示例代码:
```
import java.util.*;
public class AStar {
static class Node {
int x;
int y;
int f;
int g;
int h;
Node parent;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static List<Node> findPath(int[][] map, int startX, int startY, int endX, int endY) {
List<Node> openList = new ArrayList<>();
List<Node> closeList = new ArrayList<>();
Node startNode = new Node(startX, startY);
Node endNode = new Node(endX, endY);
openList.add(startNode);
while (openList.size() > 0) {
Node currentNode = openList.get(0);
for (int i = 1; i < openList.size(); i++) {
if (openList.get(i).f < currentNode.f) {
currentNode = openList.get(i);
}
}
openList.remove(currentNode);
closeList.add(currentNode);
if (currentNode.x == endNode.x && currentNode.y == endNode.y) {
return getPath(endNode);
}
List<Node> neighbors = getNeighbors(currentNode, map, endNode);
for (Node neighbor : neighbors) {
if (closeList.contains(neighbor)) {
continue;
}
int g = currentNode.g + 1;
boolean isBetter = false;
if (!openList.contains(neighbor)) {
isBetter = true;
neighbor.h = getDistance(neighbor, endNode);
openList.add(neighbor);
} else if (g < neighbor.g) {
isBetter = true;
}
if (isBetter) {
neighbor.parent = currentNode;
neighbor.g = g;
neighbor.f = neighbor.g + neighbor.h;
}
}
}
return null;
}
private static List<Node> getNeighbors(Node node, int[][] map, Node endNode) {
List<Node> neighbors = new ArrayList<>();
int x = node.x;
int y = node.y;
if (x > 0 && map[x - 1][y] == 0) {
neighbors.add(new Node(x - 1, y));
}
if (x < map.length - 1 && map[x + 1][y] == 0) {
neighbors.add(new Node(x + 1, y));
}
if (y > 0 && map[x][y - 1] == 0) {
neighbors.add(new Node(x, y - 1));
}
if (y < map[0
阅读全文