/**************************************************** * CS2510 Fall 2011 * Lecture #25 * Java HashMap, TreeMap; Graph Traversal: BFS, DFS ****************************************************/ import java.util.*; import tester.*; // The Graph class which contains edge links between vertices class Graph { HashMap> g; Graph() { g = new HashMap>(); } // addEdge - Add an edge to this graph, adding vertices as necessary void addEdge(Vertex v1, Vertex v2) { if (! g.containsKey(v1)) { g.put(v1, new ArrayList()); } if (! g.containsKey(v2)) { g.put(v2, new ArrayList()); } Edge e = new Edge(v1,v2); if (! g.get(v1).contains(e)) { g.get(v1).add(new Edge(v1,v2)); } } // getEdges - Returns the edges for this vertex ArrayList getEdges(Vertex v) { if (!g.containsKey(v)) { throw new RuntimeException("No such vertex " + v.name); } return g.get(v); } } // Our representation of a Vertex for a Graph class Vertex { String name; Vertex(String name) { this.name = name; } // Our int representation of a vertex: a number plus the int of the name public int hashCode() { return name.hashCode() + 6458; } // Are two vertices equal? public boolean equals(Object o) { if( o.getClass() == Vertex.class) { Vertex tmp = (Vertex) o; return this.name == tmp.name; } else { return false; } } } // Our representation of a Graph Edge between two Vertices class Edge { Vertex s; Vertex d; Edge(Vertex s, Vertex d) { this.s = s; this.d = d; } // Are two Edges equal? public boolean equals(Object o) { if( o.getClass() == Edge.class) { Edge tmp = (Edge) o; return this.s.equals(tmp.s) && this.d.equals(tmp.d); } else { return false; } } } //Breadth First Search Traversal of our Graph class BFS { Graph g; BFS(Graph g) { this.g = g; } // fromTo: Can we get from s to e in g? boolean fromTo(Vertex s, Vertex e) { LinkedList next = new LinkedList(); next.add(s); while(!next.isEmpty()) { Vertex curr = next.remove(); if (curr.equals(e)) { return true; } for(Edge edge : g.getEdges(curr)) { next.add(edge.d); } } return false; } } // Depth First Search Traversal of our Graph class DFS { Graph g; DFS(Graph g) { this.g = g; } // fromTo - Can we get from s to e in g? boolean fromTo(Vertex s, Vertex e) { LinkedList next = new LinkedList(); next.push(s); while(!next.isEmpty()) { Vertex curr = next.pop(); if (curr.equals(e)) { return true; } for(Edge edge : g.getEdges(curr)) { next.add(edge.d); } } return false; } } // Examples of our structures - to be completed tomorrow class LectureExamples { }