/** * CSE 373, Spring 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; public Graph() { this.adjacencyList = new HashMap>>(); this.vertexInfo = new HashMap>(); } public void addVertex(V v) { if (v == null) { throw new IllegalArgumentException(); } adjacencyList.put(v, new ArrayList>()); vertexInfo.put(v, new VertexInfo(v)); } public void addEdge(V from, V to, int weight) { if (from == null || to == null) { throw new IllegalArgumentException(); } // check to be sure that both from and to are in our adjacencyList if (!adjacencyList.containsKey(from) || !adjacencyList.containsKey(to)) { throw new IllegalArgumentException(); } 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) { if (from == null || to == null) { throw new IllegalArgumentException(); } // check to be sure that both from and to are in our adjacencyList if (!adjacencyList.containsKey(from) || !adjacencyList.containsKey(to)) { throw new IllegalArgumentException(); } 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) { if (v1 == null || v2 == null) { throw new IllegalArgumentException(); } // check to be sure that both from and to are in our adjacencyList if (!adjacencyList.containsKey(v1) || !adjacencyList.containsKey(v2)) { throw new IllegalArgumentException(); } this.clearVertexInfo(); List path = new ArrayList(); getDFSPath(v1, v2, path); return path; } private void getDFSPath(V v1, V v2, List path) { path.add(v1); vertexInfo.get(v1).visited = true; if (v1.equals(v2)) { return; } List> edges = adjacencyList.get(v1); for (Edge e : edges) { if (!vertexInfo.get(e.to).visited) { getDFSPath(e.to, v2, path); } if (path.get(path.size() - 1).equals(v2)) { return; } } path.remove(path.size() - 1); } 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 clearVertexInfo() { for (VertexInfo vInfo : vertexInfo.values()) { vInfo.clear(); } } }