From de3b3a614ae2f15be24b036335afc0910e411edf Mon Sep 17 00:00:00 2001 From: Harrison Date: Thu, 23 Apr 2020 21:16:43 -0500 Subject: [PATCH] Changed DFS order of operation. --- .../pathfinding/DepthFirstSearch.java | 55 +++++-------------- 1 file changed, 13 insertions(+), 42 deletions(-) diff --git a/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java b/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java index a0d0e01..6ad18f3 100644 --- a/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java +++ b/src/main/java/ca/recrown/islandsurvivalcraft/pathfinding/DepthFirstSearch.java @@ -66,32 +66,13 @@ public class DepthFirstSearch { if (coordValidatable == null) throw new IllegalStateException("Need to set a validator."); if (startNode == null) throw new IllegalStateException("Need to set the starting position."); - queue.clear(); - checkedNodes.clear(); - Node begin = startNode; - queue.add(begin); - while (!queue.isEmpty()) { - if (maxNodesSearched != -1 && checkedNodes.size() > maxNodesSearched) return false; - Node n = queue.poll(); - if (!n.equals(endNode)) { - 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 { - n.shallowCopyTo(endNode); - return true; + return findTarget(new CoordinateTargetValidatable() { + + @Override + public boolean isCoordinateTarget(int x, int y) { + return endNode.x == x && endNode.y == y; } - if (checkedNodes.add(n)) { - for (int i = 0; i < n.child.length; i++) { - Node child = n.child[i]; - if (coordValidatable.validate(child.x, child.y)) { - queue.add(child); - } - } - } - } - return false; + }); } /** @@ -114,22 +95,19 @@ public class DepthFirstSearch { while (!queue.isEmpty()) { Node n = queue.poll(); if (maxNodesSearched != -1 && checkedNodes.size() > maxNodesSearched) return false; - if (!targetValidator.isCoordinateTarget(n.x, n.y)) { + if (checkedNodes.add(n) && coordValidatable.validate(n.x, n.y)) { 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 { - foundX = n.x; - foundY = n.y; - return true; - } - if (checkedNodes.add(n)) { + if (targetValidator.isCoordinateTarget(n.x, n.y)) { + foundX = n.x; + foundY = n.y; + return true; + } for (int i = 0; i < n.child.length; i++) { Node child = n.child[i]; - if (coordValidatable.validate(child.x, child.y)) { - queue.add(child); - } + queue.add(child); } } } @@ -181,12 +159,5 @@ public class DepthFirstSearch { public int hashCode() { return Objects.hash(x, y); } - - public void shallowCopyTo(Node node) { - node.child = this.child; - node.parent = this.parent; - node.x = this.x; - node.y = this.y; - } } } \ No newline at end of file