From d44b0594576287299b5cc7bcd095009d5552dff7 Mon Sep 17 00:00:00 2001 From: Harrison Date: Tue, 21 Apr 2020 00:42:00 -0500 Subject: [PATCH] Changed DFS algorithm to use hashset. --- .../pathfinding/DepthFirstSearch.java | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java b/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java index 236e199..f5edc1b 100644 --- a/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java +++ b/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java @@ -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 checkedNodes; + private HashSet 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;