Wednesday, March 9, 2011

GIQ: depth-first graph traversal

Describe the algorithm for a depth-first graph traversal.

The use of a Stack and a Node with children...
The stack is used to traverse the tree of nodes.

import java.util.*;
public class depthfirst {

public class Node {
Object o;
Collection children;
Node(Object o) {this.o=o; children=new ArrayList();}
}
Node tree = null;
Stack stack = new Stack();

/* Push input node into Stack
* Store input node in 'node'
* Loop until stack is not empty:
* Pop stack into 'node'
* Print Node Data
* Push all child nodes into Stack
*/
void depthFirstTraversal(Node node) {
if (node == null) return;
stack.push(node);
while(!stack.empty()) {
node = (Node) stack.pop();
System.out.println("Next: "+node.o);
for(Iterator i=node.children.iterator(); i.hasNext(); ) {
Node next = (Node) i.next();
stack.push(next);
}
}
}

void breadthFirstTraversal(Node node) {
if (node == null) return;
list.add(node);
while(!list.isEmpty()) {
node = (Node) list.remove();
System.out.println("Next: "+node.o);
for(Iterator i=node.children.iterator(); i.hasNext(); ) {
Node next = (Node) i.next();
list.add(next);
}
}
}

public depthfirst(){
}

public void init() {
System.out.println(""+getAppletInfo());
System.out.println("depthfirst:");
depthFirstTraversal(tree);
System.out.println("breadthfirst:");
breadthFirstTraversal(tree);
}

int c = 0;
/* java depthfirst a b c d e f g h i
* will result in: a i d g c f b e h
* breadthfrist : a b c d i e f g h
* tree: a
* b c d i
* e f g
*/
public void createTree(Object o) {
System.out.println("push:"+o);
Node n = new Node(o);
if (tree==null) {
System.out.println("tree:"+n); // a
tree = n;
} else {
if (c<=3) {
System.out.println("c<=3:"+n); // b c d
tree.children.add(n);
} else if (c<=6) {
Iterator j = tree.children.iterator();
Node m = null;
for(int i=4; i<=c; i++) {
System.out.println("i:"+i);
m = (Node) j.next();
}
System.out.println("n:"+n); // e f g
m.children.add(n);
} else if (c<=7) {
Iterator j = tree.children.iterator();
Node m4 = (Node) j.next(); // e
j = m4.children.iterator();
Node m = null;
for(int i=7; i<=c; i++) {
System.out.println("i:"+i);
m = (Node) j.next();
}
System.out.println("n:"+n); // h
m.children.add(n);
} else {
System.out.println("else:"+n); // i
tree.children.add(n);
}
}
c++;
}

public String getAppletInfo() {
return "depth first graph by Douglas A. Bauman";
}

static public void main(String[] args) {
depthfirst df = new depthfirst();
for(int i=0; i<args.length; i++) {
df.createTree(args[i]);
}
df.init();
}
}

No comments:

Post a Comment