-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAStarAlgorithm.java
88 lines (73 loc) · 2.53 KB
/
AStarAlgorithm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.*;
class Node {
int x, y;
int g, h;
Node parent;
public Node(int x, int y, int g, int h, Node parent) {
this.x = x;
this.y = y;
this.g = g;
this.h = h;
this.parent = parent;
}
public int getF() {
return g + h;
}
}
public class AStarAlgorithm {
static final int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public static List<Node> aStarSearch(int[][] grid, Node start, Node end) {
PriorityQueue<Node> openList = new PriorityQueue<>(Comparator.comparingInt(Node::getF));
Set<String> closedSet = new HashSet<>();
openList.add(start);
while (!openList.isEmpty()) {
Node current = openList.poll();
closedSet.add(current.x + "," + current.y);
if (current.x == end.x && current.y == end.y) {
return buildPath(current);
}
for (int[] dir : directions) {
int newX = current.x + dir[0];
int newY = current.y + dir[1];
if (isInBounds(grid, newX, newY) && grid[newX][newY] == 0 && !closedSet.contains(newX + "," + newY)) {
int gCost = current.g + 1;
int hCost = Math.abs(newX - end.x) + Math.abs(newY - end.y);
Node neighbor = new Node(newX, newY, gCost, hCost, current);
openList.add(neighbor);
}
}
}
return null; // Path not found
}
private static boolean isInBounds(int[][] grid, int x, int y) {
return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length;
}
private static List<Node> buildPath(Node end) {
List<Node> path = new ArrayList<>();
while (end != null) {
path.add(0, end);
end = end.parent;
}
return path;
}
public static void main(String[] args) {
int[][] grid = {
{0, 1, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0}
};
Node start = new Node(0, 0, 0, 0, null);
Node end = new Node(4, 4, 0, 0, null);
List<Node> path = aStarSearch(grid, start, end);
if (path != null) {
System.out.println("Path found:");
for (Node node : path) {
System.out.print("(" + node.x + ", " + node.y + ") ");
}
} else {
System.out.println("No path found.");
}
}
}