// Stephanie's class notes. // sorely missing comments and docstrings. sorry. // Graph implemented with adjacency list // Note: I have implemented the graph as a digraph. If you want to connection // node A to node B, it puts in an edge from A to B, but not the corresponding // edge from B to A. import java.util.*; public class Graph1 { private ArrayList nodes; public static class GraphNode { private ArrayList neighbors; String label; boolean marked; public GraphNode() { this.neighbors = new ArrayList(); this.label = ""; this.marked = false; } public GraphNode(String label) { this.neighbors = new ArrayList(); this.label = label; this.marked = false; } // make a directed connection from this node to the other node public void connectTo( GraphNode other ) { this.neighbors.add( other ); } public String toString() { String ret = this.label + ":"; for (GraphNode n: this.neighbors) ret += " " + n.label; return ret; } } // end class GraphNode public Graph1() { nodes = new ArrayList(); } public void connect( GraphNode fromNode, GraphNode toNode ) { if (! this.nodes.contains( fromNode )) this.nodes.add( fromNode ); if (! this.nodes.contains( toNode )) this.nodes.add( toNode ); fromNode.connectTo( toNode ); } public void printAll() { for (GraphNode n: nodes) System.out.println( n ); } public void generalTraversalPrint(GraphNode n0) { // unmark all nodes for (GraphNode n: nodes) n.marked = false; ArrayDeque nbs = new ArrayDeque(); nbs.add( n0 ); while (!nbs.isEmpty()) { GraphNode n = nbs.remove(); n.marked = true; System.out.println( n ); for (GraphNode p: n.neighbors) { if (!p.marked && !nbs.contains(p)) nbs.add( p ); } } } public static void main( String[] args ) { Graph1 g = new Graph1(); GraphNode n1 = new GraphNode( "n1" ); GraphNode n2 = new GraphNode( "n2" ); GraphNode n3 = new GraphNode( "n3" ); g.connect( n1, n2 ); g.connect( n3, n2 ); g.printAll(); System.out.println( "Traversing from n1" ); g.generalTraversalPrint( n1 ); System.out.println( "Traversing from n2" ); g.generalTraversalPrint( n2 ); System.out.println( "Traversing from n3" ); g.generalTraversalPrint( n3 ); } }