/** * CSE 373, Winter 2011, Jessica Miller * A class for a directed graph. * Implemented by an adjacency list representation of a graph. */ import java.util.*; public class Graph implements IGraph { private Map>> adjacencyList; // [vertices] -> [edge] private Map> vertexInfo; // [vertex] -> [info] public Graph() { this.adjacencyList = new HashMap>>(); this.vertexInfo = new HashMap>(); } public void addVertex(V v) { if (v == null) { throw new IllegalArgumentException("null"); } adjacencyList.put(v, new ArrayList>()); vertexInfo.put(v, new VertexInfo(v)); } public void addEdge(V from, V to, int weight) { List> edgeList = adjacencyList.get(from); if (edgeList == null) { throw new IllegalArgumentException("source vertex not in graph"); } Edge newEdge = new Edge(from, to, weight); edgeList.add(newEdge); } public boolean hasEdge(V from, V to) { return getEdge(from, to) != null; } public Edge getEdge(V from, V to) { List> edgeList = adjacencyList.get(from); if (edgeList == null) { throw new IllegalArgumentException("source vertex not in graph"); } for(Edge e : edgeList) { if (e.to.equals(to)) { return e; } } return null; } public boolean hasPath(V v1, V v2) { return getDFSPath(v1, v2) != null; } public List getDFSPath(V v1, V v2) { clearVertexInfo(); List path = new ArrayList(); getDFSPath(v1, v2, path); if (path.isEmpty()) { return null; } else { return path; } } private List getDFSPath(V v1, V v2, List path) { path.add(v1); VertexInfo vInfo = vertexInfo.get(v1); vInfo.visited = true; if (v1.equals(v2)) { return path; } List> edges = this.adjacencyList.get(v1); for (Edge e : edges) { VertexInfo vInfo2 = vertexInfo.get(e.to); if (!vInfo2.visited) { getDFSPath(e.to, v2, path); if (path.get(path.size() - 1).equals(v2)) { return path; } } } path.remove(v1); return path; } public String toString() { Set keys = adjacencyList.keySet(); String str = ""; for (V v : keys) { str += v + ": "; List> edgeList = adjacencyList.get(v); for (Edge edge : edgeList) { str += edge + " "; } str += "\n"; } return str; } protected final void clearVertexInfo() { for (VertexInfo info : this.vertexInfo.values()) { info.clear(); } } }