Changed DFS algorithm to use hashset.

This commit is contained in:
Harrison Deng 2020-04-21 00:42:00 -05:00
parent f5e3435d8b
commit d44b059457

View File

@ -1,7 +1,8 @@
package ca.recrown.islandsurvivalcraft.pathfinding;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
@ -10,10 +11,10 @@ public class DepthFirstSearch {
private CoordinateValidatable validatable;
private Node startNode;
private Node endNode;
private ArrayList<Node> checkedNodes;
private HashSet<Node> checkedNodes;
public DepthFirstSearch() {
checkedNodes = new ArrayList<>();
checkedNodes = new HashSet<>();
}
public DepthFirstSearch(CoordinateValidatable validatable) {
@ -62,7 +63,7 @@ public class DepthFirstSearch {
n.shallowCopyTo(endNode);
return true;
}
if (!n.check()) {
if (checkedNodes.add(n)) {
for (int i = 0; i < n.child.length; i++) {
Node child = n.child[i];
if (validatable.validate(child.x, child.y)) {
@ -97,7 +98,7 @@ public class DepthFirstSearch {
endNode = n;
return true;
}
if (!n.check()) {
if (checkedNodes.add(n)) {
for (int i = 0; i < n.child.length; i++) {
Node child = n.child[i];
if (validatable.validate(child.x, child.y)) {
@ -134,14 +135,6 @@ public class DepthFirstSearch {
return distance;
}
public boolean check() {
if (checkedNodes.contains(this)) {
return true;
}
checkedNodes.add(this);
return false;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Node) {
@ -153,6 +146,11 @@ public class DepthFirstSearch {
return false;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
public void shallowCopyTo(Node node) {
node.child = this.child;
node.parent = this.parent;