/** * CSE 373, Spring 2012 * 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; public Graph() { adjacencyList = new HashMap>>(); vertexInfo = new HashMap>(); } public void addVertex(V v) { checkForNull(v); adjacencyList.put(v, new ArrayList>()); vertexInfo.put(v, new VertexInfo(v)); } public void addEdge(V from, V to, int weight) { checkVertices(from, to); Edge edge = new Edge(from, to, weight); adjacencyList.get(from).add(edge); } public boolean hasEdge(V from, V to) { return getEdge(from, to) != null; } public Edge getEdge(V from, V to) { checkVertices(from, to); List> edges = adjacencyList.get(from); for (Edge e : edges) { if (e.to.equals(to)) { return e; } } return null; } public boolean hasPath(V v1, V v2) { return !getDFSPath(v1, v2).isEmpty(); } public List getDFSPath(V v1, V v2) { checkVertices(v1, v2); clearVisited(); List path = new ArrayList(); return getDFSPath(v1, v2, path); } private void clearVisited() { for (VertexInfo info : vertexInfo.values()) { info.clear(); } } private List getDFSPath(V v1, V v2, List path) { path.add(v1); vertexInfo.get(v1).visited = true; if (v1.equals(v2)) { return path; } List> edges = adjacencyList.get(v1); for (Edge e : edges) { if (vertexInfo.get(e.to).visited) { continue; } if (getDFSPath(e.to, v2, path) != null) { return path; } } path.remove(path.size() - 1); return null; } 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; } private void checkForNull(Object arg) { if (arg == null) { throw new NullPointerException("Argument must not be null"); } } private void checkVertices(V v1, V v2) { checkForNull(v1); checkForNull(v2); if (!adjacencyList.containsKey(v1)) { throw new IllegalArgumentException("Vertex not found in graph: " + v1); } if (!adjacencyList.containsKey(v2)) { throw new IllegalArgumentException("Vertex not found in graph: " + v2); } } }