Changed DFS order of operation.

This commit is contained in:
Harrison Deng 2020-04-23 21:16:43 -05:00
parent e45d642791
commit de3b3a614a

View File

@ -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;
}
}
}