-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPathfinder4D.java
68 lines (57 loc) · 2.62 KB
/
Pathfinder4D.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
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.PriorityQueue;
/**
* @author Sara Azzouz <sazzouz@umich.edu>
*/
public class Pathfinder4D {
private Grid4D gr;
public Pathfinder4D(Grid4D gr){
this.gr = gr;
}
public ArrayList<int[]> findPath(int[] start, int[] end){
if(gr.isValid(start[0], start[1], start[2]) && gr.isValid(end[0], end[1], end[2])){
PriorityQueue<Node4D> openSet = new PriorityQueue<>(Collections.reverseOrder());
HashSet<Node4D> closedSet = new HashSet<>();
Node4D endNode = gr.getNode(end[0], end[1], end[2]);
Node4D startNode = gr.getNode(start[0], start[1], start[2]);
openSet.add(gr.getNode(start[0], start[1], start[2]));
while(!openSet.isEmpty()){
Node4D currentNode = openSet.poll();
closedSet.add(currentNode);
if(currentNode == endNode){
return retrace(startNode,endNode);
}
for(Node4D neighbor : gr.getNeighbors(currentNode)){
if(closedSet.contains(neighbor)) {continue;}
double newMoveCost2Neighbor = currentNode.getGCost()+gr.getDistance(currentNode, neighbor);
if(newMoveCost2Neighbor < neighbor.getGCost() || !openSet.contains(neighbor)) {
neighbor.setGCost(newMoveCost2Neighbor);
neighbor.setHCost(gr.getDistance(neighbor, endNode));
neighbor.setParent(currentNode);
if(!openSet.contains(neighbor)){openSet.add(neighbor);}
else{
openSet.remove(neighbor);
openSet.add(neighbor);
}
}
}
}
}
return null;
}
private ArrayList<int[]> retrace(Node4D startNode, Node4D endNode){
ArrayList<int[]> path = new ArrayList<>();
Node4D currentNode = endNode;
while(currentNode != startNode){
int[] pos = currentNode.getPosition();
path.add(new int[] {pos[0], pos[1], pos[2]});
currentNode = currentNode.getParent();
}
Collections.reverse(path);
int[] pos = startNode.getPosition();
path.add(0,new int[] {pos[0], pos[1], pos[2]});
return path;
}
}