// Stephanie's class notes. // sorely missing comments and docstrings. sorry. // Graph implemented with adjacency matrix // 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 Graph4 { private int[][] edges; private GraphNode[] nodes; public static class GraphNode { String label; public GraphNode() { this.label = ""; } public GraphNode(String label) { this.label = label; } public String toString() { return this.label; } } // end class GraphNode // I have the constructor make all the nodes, too. // Depending on how you want to use this class, that could have // been a terrible decision. public Graph4(int numNodes) { this.nodes = new GraphNode[numNodes]; for (int i = 0; i < numNodes; i++) this.nodes[i] = new GraphNode( "n" + Integer.toString(i) ); this.edges = new int[numNodes][numNodes]; } public void connect( int fromNode, int toNode ) { this.edges[fromNode][toNode] = 1; } public void printAll() { for (int fromIdx=0; fromIdx < this.edges.length; fromIdx++) { GraphNode n = this.nodes[fromIdx]; System.out.print( n + ": "); for (int toIdx = 0; toIdx < this.edges.length; toIdx++) { if (this.edges[fromIdx][toIdx] > 0) System.out.print( this.nodes[toIdx] + " " ); } System.out.println(); } } public static void main( String[] args ) { Graph4 g = new Graph4(3); g.connect( 0, 1 ); g.connect( 2, 1 ); g.printAll(); } }