Implemented DFS algorithm.

Untested.
This commit is contained in:
Harrison Deng 2020-04-20 16:24:49 -05:00
parent 85dd6e6e3d
commit 4b9c5ca440
2 changed files with 110 additions and 0 deletions

View File

@ -0,0 +1,5 @@
package ca.recrown.islandsurvivalcraft.pathfinding;
public interface CoordinateValidatable {
public boolean validate(int x, int y);
}

View File

@ -0,0 +1,105 @@
package ca.recrown.islandsurvivalcraft.pathfinding;
import java.util.PriorityQueue;
public class DepthFirstSearch {
private PriorityQueue<Node> queue;
private CoordinateValidatable validatable;
private Node startNode;
private Node endNode;
public DepthFirstSearch(CoordinateValidatable validatable) {
queue = new PriorityQueue<>();
this.validatable = validatable;
}
public void setStartNode(int xGoal, int yGoal, int x, int y) {
startNode = new Node(null, xGoal, yGoal, x, y);
}
public Node getTree() {
return startNode;
}
public Node getEndNode() {
return endNode;
}
public Node getParentOfNode(Node node) {
return node.parent;
}
public void deleteTree() {
startNode = null;
endNode = null;
}
public boolean isConnected() {
queue.clear();
Node begin = startNode;
queue.add(begin);
while (!queue.isEmpty()) {
Node n = queue.poll();
if (!(n.x == n.xGoal && n.y == n.yGoal)) {
n.child[0] = new Node(n, n.x + 1, n.y);
n.child[1] = new Node(n, n.x - 1, n.y);
n.child[2] = new Node(n, n.x, n.y + 1);
n.child[3] = new Node(n, n.x, n.y - 1);
} else {
endNode = n;
return true;
}
if (!n.check()) {
for (int i = 0; i < n.child.length; i++) {
validatable.validate(n.child[i].x, n.child[i].y);
queue.add(n.child[i]);
}
}
}
return false;
}
private class Node implements Comparable<Node> {
public Node[] child;
public final Node parent;
public int x;
public int y;
private boolean checked = false;
private final int xGoal;
private final int yGoal;
public Node(Node parent, int xGoal, int yGoal, int x, int y) {
this.parent = parent;
child = new Node[4];
this.xGoal = xGoal;
this.yGoal = yGoal;
this.x = x;
this.y = y;
}
public Node(Node parent, int x, int y) {
this(parent, parent.xGoal, parent.yGoal, x, y);
}
@Override
public int compareTo(Node o) {
return Math.round(distanceToGoal() - o.distanceToGoal());
}
public float distanceToGoal() {
float distanceX = xGoal - this.x;
float distanceY = yGoal - this.y;
float distance = (float) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
return distance;
}
public boolean check() {
if (!checked) {
checked = true;
return false;
}
return true;
}
}
}