package graph; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * This class represents directed and undirected graphs of vertices. * Graphs are internally represented using adjacency lists. * @author tcolburn */ public class Graph { /** * Constructs a new graph given lists of vertices and edges. * @param vertices A list of graph vertices * @param edges A list of graph edges * @param directed Whether the graph is directed or not */ public Graph(List<Vertex> vertices, List<Edge> edges, boolean directed) { this.vertices = vertices; this.directed = directed; adj_hash = new Hashtable<Vertex, List<Vertex>>(); Iterator<Vertex> vertexIterator = vertices.iterator(); while ( vertexIterator.hasNext() ) { Vertex v = (Vertex) vertexIterator.next(); adj_hash.put(v, new LinkedList<Vertex>()); } Iterator<Edge> iter = edges.iterator(); while (iter.hasNext()) { Edge e = iter.next(); addEdge(e.getV1(), e.getV2()); } } /** * Adds an edge (v1, v2) to this graph. * If the graph is undirected, (v2, v1) is also added. * @param v1 The first vertex in the edge * @param v2 The second vertex in the edge */ private void addEdge(Vertex v1, Vertex v2) { adj_hash.get(v1).add(v2); if (!directed) { adj_hash.get(v2).add(v1); } } /** * Tests whether a pair of vertices forms an edge in this graph. * @param vertex1 The first vertex * @param vertex2 The second vertex * @return Whether there is an edge from the first vertex to the second */ public boolean isEdge(Vertex vertex1, Vertex vertex2) { return adj_hash.get(vertex1).contains(vertex2); } /** * Accessor for a list of vertices making up this graph. * @return A list of vertices */ public List<Vertex> getVertices() { return vertices; } /** * Creates a string representation of this graph's adjacency list for testing. * @return The string representation of the adjacency list */ public String toString() { StringBuffer buffer = new StringBuffer(); Iterator vertexIterator = vertices.iterator(); while ( vertexIterator.hasNext() ) { Vertex vertex = (Vertex) vertexIterator.next(); buffer.append("\n" + vertex.getName()); List<Vertex> adjList = adj_hash.get(vertex); if ( adjList == null ) continue; Iterator listIterator = adjList.iterator(); while ( listIterator.hasNext() ) { Vertex adjVertex = (Vertex) listIterator.next(); buffer.append(" -> " + adjVertex.getName()); } } return buffer.toString(); } /** * Whether this graph is directed or not. */ private boolean directed; /** * The vertex's adjacency lists are stored in a hash table whose * keys are vertices and whose values are lists of vertices. */ private Hashtable<Vertex, List<Vertex>> adj_hash; /** * A list of vertices in this graph. This list is necessary because a * vertex may not get into the hash table if there is no edge from it. */ private List<Vertex> vertices; }