A* algorithm change node parent - java

I am confused about changing the parent of a node in the A* algorithm.
There seem to be different ways of choosing a new parent:
In this video:
https://www.youtube.com/watch?v=KNXfSOx4eEE
It says that you should check this:
G cost currentNode + movement cost from currentNode <= G cost openListNode
If that is the case then we should replace the parent node of the openListNode to the current node.
But in this implementation:
http://www.codebytes.in/2015/02/a-shortest-path-finding-algorithm.html
it has the following code:
static void checkAndUpdateCost(Cell current, Cell t, int cost){
if(t == null || closed[t.i][t.j])return;
int t_final_cost = t.heuristicCost+cost;
boolean inOpen = open.contains(t);
if(!inOpen || t_final_cost<t.finalCost){
t.finalCost = t_final_cost;
t.parent = current;
if(!inOpen)open.add(t);
}
}
It checks the final cost which is : G + H , which contradicts the other explanation, as it should be only G cost, not the sum of the G cost and the heuristic.
Can someone explain me, which one is correct ?, is the implementation wrong ?

Bottom Line Up Front (BLUF):
The video is accurate, but here's the key: The node's parent should only be updated in one of the following two cases: 1.) when encountering the node for the first time, or 2.) when you find a more efficient path to a node that was previously encountered. Also, do not use the heuristic when updating a node's parent.
Additional Details:
Below is a working implementation based on Wikipedia's Pseudocode; I've added extra comments to differentiate the two cases.
If !isOpen && !isClosed is true then the node has never been seen before; therefore, it's parent should be set to the current node, and it should be added to the open set. But if !isOpen && !isClosed is false, then the node was already in the open set (i.e. if isOpen is true) or if it was previously closed (i.e. if isClosed is true). Therefore, we need to check if the current path is more efficient than the one which previously caused the neighbor node to be in the open/closed set-- this is why we check if costFromStart < g_score[neighborNode.x][neighborNode.y]
while (!openList.isEmpty()) {
Pair node = openList.dequeueMin().getValue();
if (node.equals(goal)) {
// construct the path from start to goal
return reconstruct_path(goal);
}
for (Pair neighborNode : getNeighbors(node,goal)) {
if (neighborNode == null) continue;
boolean isOpen = openSet.contains(neighborNode);
boolean isClosed = closedSet.contains(neighborNode);
double costFromStart = g_score[node.x][node.y]+MOVEMENT_COST;
// check if the neighbor node has not been
// traversed or if a shorter path to this
// neighbor node is found.
if (
(!isOpen && !isClosed) // first time node has been encountered
|| //or
costFromStart < g_score[neighborNode.x][neighborNode.y]) //new path is more efficient
{
came_from[neighborNode.x][neighborNode.y] = node;
g_score[neighborNode.x][neighborNode.y] = costFromStart;
h_score[neighborNode.x][neighborNode.y] =
estimateCost(neighborNode,goal);
if (isClosed) {
closedSet.remove(neighborNode);
}
if (!isOpen) {
openList.enqueue(neighborNode,costFromStart);
openSet.add(neighborNode);
}
}
}
closedSet.add(node);
}

Related

Graph path finder

i am trying to find a path in between two nodes(sourcenode and targetnode). i came up with this code but i cant seem to make it recursively find a path. i even set the nodes to null if the target node is found but i keep getting a stack overflow error.
public void findPathBetween(Node sourceNode, Node targetNode){
//find a path between the sourceNode and targetNode
//select the nodes and edges along the path if one exists.
ArrayList<Node> nodesToSearch = new ArrayList<Node>();
nodesToSearch.add(sourceNode);
//basis
if(sourceNode == null || targetNode == null) return;
//recursion
ArrayList<Node> newNodesToSearch = new ArrayList<Node>(); //get nodes for next level to search
for(Node aNode : nodesToSearch) {
for (Node neighbour : aNode.getNeighbours()) {
if (neighbour != targetNode && newNodesToSearch.isEmpty()) {
newNodesToSearch.add(neighbour);
neighbour.setSelected(true);
edgeBetween(aNode, neighbour).setSelected(true);
sourceNode = neighbour;
}
if (neighbour == targetNode) {
sourceNode = null;
targetNode = null;
return;
}
}
}
if(sourceNode != null &&targetNode != null) {
findPathBetween(sourceNode, targetNode);
}
}
You are storing the state inside the recursion function, and don't pass it to the next iteration. Thus you are simply running one function over and over without changing its arguments and the state that affects its execution.
I do not want to correct your code because I would have to guess you intents in order to provide a good explanation.
Anyway I think that you were trying to implement DFS, so I suggest you to take a look at some working implementations. Just google them, there are plenty, e.g. this one comes with a piece of theory, is simple, and was written by Robert Sedgewick, so it can be trusted.

Change the value of the leaves of a tree with the sum of the path from root to leaf

I have to create a function that took a tree t not empty, change the content of each leaf in its field by putting the sum of the values contained in the nodes of the path from the root to the leaf (including root and leaf).
So I created this:
void sum(BinTree t) {
while(!t.isLeaf()) {
sumL += sum(t.left);
sumR += sum(t.right);
}
t.element = ?;
}
boolean isLeaf(BinTree t) {
return t.left == null && t.right == null;
}
What should I put in place of "?"? I don't think that the function is correct..
I'm unable to create recursive functions for the binary trees, I find them very complicated..
Thanks
EDIT: I changhed my method:
void leafSum(BinTree t) {
sumLeaf(root, 0);
}
void leafSum(BinTree t, int tot) {
if(t->left == NULL && t->right == NULL)
t->elem = tot;
else {
sumLeaf(t->left, tot + t->elem);
sumLeaf(t->right, tot + t->elem);
}
}
Rather than providing a solution I'll give a few hints to help you along. Ask questions if any of it isn't clear.
The basic algorithm you are looking for is: for each node if it's a leaf then store the sum, if it's not a leaf then repeat for both child nodes.
While recursion isn't essential it will make the solution simpler in this case. It's not complex: the basic rule is to always have a termination condition (in your case, that you are looking at a leaf) before recursing.
You should pass a running total to the function so that you don't need to look back up the tree once you get to a leaf. That's not complex: just add the current value for the node to the running total before storing it (for leaves) or passing it to child node (for non-leaves).
Start with a running total of zero when you call the function for the root node.
That's about it - you should be able to come up with a solution from those hints.

Deleteing a Node in a Binary tree

Iunderstand the basis of a deletion algorithm in a Binary Search tree and have created the following code to delete the largest value from the tree.
public void DelLargest()
{
Node<T> del = this;
boolean child = this.left.empty();
boolean child2 = this.right.empty();
right.DelLargest();
if(child && child2)
this.head = null;
else if(child == true && child2 == false)
this.head = left;
}
Basically what I have is that the recursion runs until 'this' is the rightmost node and then checks two cases, whether 'this' is a leaf, or whether 'this' has a left child. (The other case normally associated with this kind of algorithm is redundant because in finding the node with the largest value, I have gone as right as I can go.) The trouble I am having is getting the current node to then either point to null or to the value at Node left.
Note : This is what my instructor referred to as a "modern" Binary search Tree wherein a vertex or "filled" node and a nil or "empty" node are two subclasses of Interface Node which define the characteristics of each type.
I've managed to narrow the problem down to the fact that I do not have a method that returns a value of a given Node. Working on that now, input would be appreciated.
As suggested in the other answer you should use iterative approach.
In a BST the largest value is the rightmost node.
So do a scan and keep going right until you hit a null.
In the scan keep track of three nodes. (gpnode, pnode, node).
Once the scan is done you will have (gpnode,pnode,null)
Now there are 2 cases.
case 1:
pnode is a leaf. So change the edge (gpnode,pnode) to (gpnode,null)
case 2: (EDITED)
pnode.lChild is not null. Note that pnode.rChild will be null as the search would have terminated at that point.
Now change the edge (gpnode,pnode) to (gpnode,pnode.lChild)
Here is the pseudo code:
public class Node
{
long key;
Node lChild;
Node rChild;
}
public void DelLargest()
{
Node gpnode = null;
Node pnode = null;
Node node = root;
while(node != null) // keep going right until a null is reached
{
gpnode = pnode;
pnode = node;
node = node.rChild;
}
if(pnode.lChild == null) // its a leaf node So change the edge (gpnode,pnode) to (gpnode,null)
{
if(gpnode.lChild == pnode)
{
gpnode.lChild = null;
}
else
{
gpnode.rChild = null;
}
}
else // copy lChild's key to this node and delete lChild
{
if(gpnode.lChild == pnode)
{
gpnode.lChild = pnode.lChild;
}
else
{
gpnode.rChild = pnode.lChild;
}
}
}
You've got the right idea. What you want to do is keep a reference to the right most nodes parent, and the right most nodes left child so then when you delete it you can attach the two.
Here's an iterative solution. This will generally be more efficient than recursion, but if you want recursion you should be able to adapt it:
public void delLargest() {
// get rightmost node's parent
Node<T> current = root;
while(current.right != null && current.right.right != null) {
current = current.right;
}
// get the rightmost nodes left node
Node<T> left = current.right.left;
// attach the parent and left
current.right = left;
// nothing points to the right most node anymore, so it will be garbage collected
}

java alogrithm: find pre/next leaf node that meet special condition from any node in a tree

I need to write a function to find previous/next leaf node that meet special condition from any node in a singly rooted tree. (in the parent first order)
The API would be something like this:
Node findNextLeafNode(Node currentNode, Condition condition);
Node findPretLeafNode(Node currentNode, Condition condition);
where currentNode is any node in a tree, and Node is defined as:
interface Node{
/** #return the Node's parent or null if Node is root */
Node getParent();
/** #return true if node is root */
boolean isRoot();
/** #return non-null array of child nodes (zero length for leaf nodes) */
Node[] getChildren();
/** #return the number of child nodes. If node is leaf, value is 0 */
int getChildCount();
}
And the Condition interface defines the semantics of checking a constraint against a given Node.
interface Condition{
/** #return true if provided node meets the condition */
boolean check(Node node);
}
My question:
Is there an existing library or algorithm for such a common scenario? I am open to either stack based or recursive algorithms. Pseudocode, links to open source libraries, or if you care to share you own code, would be appreciated.
(If not, I need to spend time to invent the same wheel again and paste it here later for sharing.)
Thanks.
-----------------------------write a method to getNext()........
// currentNode must be descendant of root
public static Node getNextNode(Node currentNode, Node root)
{
// 1. if is has child, next is its first child
if (currentNode.getChildSize() > 0) {
return currentNode.getChildren()[0];
}
// 2. if it has no child, check if its is the last child of his parent
else {
// if it is root and has no children, return null
if (currentNode == root) {
return null;
}
// else should have parent which is or under root;
Node parent = currentNode.getParent();
int index = getIndex(currentNode);
if (!isLastofParent(currentNode)) {
// ----a. if not last, next is his parent's next
return currentNode.getParent().getChildren()[index + 1];
}
else {
// ----b. if it is the last one, return its parent's next right if there is. while until root
Node tmp = parent;
while (tmp != root) {
int parentIndex = getIndex(tmp);
if (!isLastofParent(tmp)) {
return tmp.getParent().getChildren()[parentIndex + 1];
}
tmp = tmp.getParent();
}
}
}
return null;
}
private static boolean isLastofParent(Node node)
{
if (getIndex(node) == node.getParent().getChildSize() - 1) {
return true;
}
return false;
}
private static int getIndex(Node currentNode)
{
Node parent = currentNode.getParent();
for (int i = 0; i < parent.getChildSize(); i++) {
if (parent.getChildren()[i] == currentNode) {
return i;
}
}
//TODO: error condition handling, will not happen if tree not change
return -1;
}
------------------------a full search is much easier............
public static Node getNextFailNode(Node currentNode, Node root, Condition condition)
{
boolean foundCurrentNode = false;
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node tmp = stack.pop();
System.out.println("-popup---------" +tmp+ " ");
if (foundCurrentNode && checkCondition(tmp, condition)) {
return tmp;
}
if (tmp == currentNode) {
foundCurrentNode = true;
}
if (tmp.getChildSize() > 0) {
for (int i = tmp.getChildSize() - 1; i >= 0; i--) {
stack.push(tmp.getChildren()[i]);
}
}
}
return null;
}
This maybe way overblown for what you need, but it can support what you want:
There is a graph traversal language: Gremlin. Typically bolted on top of something like Neo4j, but any graph data structure (e.g. a singly rooted directed tree) can be wrapped to support the API. Take a look at Blueprints projects to find out how it is done.
[edit: for something less heavy]
Perhaps JGraphT is what you want. Also take a look at this question on SO. It is not an exact duplicate, but you should find it helpful.
Write an iterator for your tree that can be initialized from any node and uses pre/in/post-order traversal (Of course it should be bi-directional).
This is basically writing one simple algorithm that at least to me seem basic.
Once you have an iterator all you need is to iterate your way to the next node which is a leaf and the condition holds for it.
If you have trouble with any specific part just ask and I'll improve my answer.
Based on the fact that you already have defined your interfaces, and you say the graph-traversal libraries are too heavyweight, you probably should just write it yourself. It would be an absolutely trivial amount of code. (This page contains some code if you need help.)
(One suggestion for your API: don't put a boolean isRoot(); method on Node, that's a waste of bits unless you have a very good reason to do so. The code that builds the tree should just refer to the root node.)

Java, Binary tree remove method

I am trying to write a remove(node cRoot, Object o) function for a sorted binary tree.
Here is what I have so far:
private boolean remove(Node cRoot, Object o) {
if (cRoot == null) {
return false;
}
else if (cRoot.item.equals(o)) {
//erase node fix tree
return true;
}
else if (((Comparable)item).compareTo(cRoot.item)<=0){
return remove(cRoot.lChild, o);
}
else {
return remove(cRoot.rChild,o);
}
}
It does not work correctly. To delete a node you have to repair the tree to fix the hole. How should this be done?
There are generally two ways of performing a remove on the tree:
First method:
Remove the node, then replace it with either child. Then, resort the tree by doing parent-child swapping until the tree is once again sorted.
The second method:
Traverse the tree to find the next (highest or lowest) value that belongs as the root*, if it is a leaf node, swap that with the root, then trim off the value you want to remove. If it is an internal node, you will have to recursively call remove on that node. Repeat until a leaf node is removed.
*What I mean is, if you convert your BST into a sorted list, then you will want to pick either value to the left or right of the root as the new root. I.e. leftmost child of the right subtree, or right most child of the left subtree.
The basic pseudo-code for erasing a node from a sorted tree is pretty simple:
erase the node value
find child node with maximum value
make it the root node
if it had children - goto 2 recursively
Basically what you are doing is bubbling nodes up the tree, each time the maximum of the children node in each node, so that in the end you stay with a sorted tree, and only one node missing at the end of the full path you went.
Also - see wikipedia on the subject, they have some sample code in C as well.
In the simple case3 you can use next algorithm:
if(removed node had left child)
{
place left child instead of removed node;
most_right = most right leaf in the left subtree;
move right child of removed node as right child of most_right;
}
else
{
place right child instead of removed node
}
In more complicated case you may need to rebalance your tree (see AVL trees, http://www.cmcrossroads.com/bradapp/ftp/src/libs/C++/AvlTrees.html for C++ example)
leaf-delete node
1-child Promote the subtree
2-child case replace the node with either
in order successor or predecessor
left most of the right subtree or
right most of the left subtree
I found this code on Habrahabr. I've just added comments.
public void remove (T1 k){
Node<T1,T2> x = root, y = null;
// from while to if(x == null) - searching for key
while(x != null){
int cmp = k.compareTo(x.key);
if(cmp == 0){
break; // quit cycle if key element is found
} else {
y = x;
if(cmp < 0){
x = x.left;
} else {
x = x.right;
}
}
}
if(x == null) return; // if key is not found or tree is empty
if(x.right == null){ // if element found has not right child
if(y == null){ // if element found is root & has not right child
root = x.left;
} else { // if element found is not root & has not right child
if(x == y.left) y.left = x.left;
else y.right = x.left;
}
} else { // element found has right child, so search for most left of rights
Node<T1,T2> mostLeft = x.right;
y = null;
while(mostLeft.left != null) {
y = mostLeft;
mostLeft = mostLeft.left;
}
if(y == null){ // if right child of element found has not left child
x.right = mostLeft.right;
} else { // if right child of element found has left child
y.left = mostLeft.right;
}
x.key = mostLeft.key;
x.value = mostLeft.value;
}
}

Categories