A算法是一种启发式搜索算法,用于寻找从起点到终点的最短路径。以下是使用Java语言实现A算法的示例代码:
import java.util.*;
class Node {
int x, y;
Node parent;
double gCost, hCost, fCost;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public class AStarAlgorithm {
private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public static List<Node> findPath(int[][] grid, Node start, Node end) {
PriorityQueue<Node> openList = new PriorityQueue<>(Comparator.comparingDouble(node -> node.fCost));
Set<Node> closedList = new HashSet<>();
start.gCost = 0;
start.hCost = heuristic(start, end);
start.fCost = start.gCost + start.hCost;
openList.add(start);
while (!openList.isEmpty()) {
Node currentNode = openList.poll();
closedList.add(currentNode);
if (currentNode.equals(end)) {
return buildPath(currentNode);
}
for (int[] direction : DIRECTIONS) {
int newX = currentNode.x + direction[0];
int newY = currentNode.y + direction[1];
if (isValid(grid, newX, newY) && !closedList.contains(new Node(newX, newY))) {
Node neighbor = new Node(newX, newY);
neighbor.parent = currentNode;
neighbor.gCost = currentNode.gCost + 1;
neighbor.hCost = heuristic(neighbor, end);
neighbor.fCost = neighbor.gCost + neighbor.hCost;
if (!openList.contains(neighbor)) {
openList.add(neighbor);
}
}
}
}
return null; // No path found
}
private static boolean isValid(int[][] grid, int x, int y) {
return x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && grid[x][y] == 0;
}
private static double heuristic(Node a, Node b) {
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
private static List<Node> buildPath(Node node) {
List<Node> path = new ArrayList<>();
while (node != null) {
path.add(node);
node = node.parent;
}
Collections.reverse(path);
return path;
}
public static void main(String[] args) {
int[][] grid = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0}
};
Node start = new Node(0, 0);
Node end = new Node(4, 4);
List<Node> path = findPath(grid, start, end);
if (path != null) {
for (Node node : path) {
System.out.println("[" + node.x + ", " + node.y + "]");
}
} else {
System.out.println("No path found");
}
}
}
这段代码定义了一个Node
类,用于表示地图上的每个点。AStarAlgorithm
类包含了实现A*算法的主要逻辑。findPath
方法接受一个二维数组grid
作为地图,以及起点和终点节点。它返回一个包含从起点到终点的路径的节点列表。如果没有找到路径,它将返回null
。