aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/AdjMapGraph.java
blob: d5749a956ed5b03516cd5ead9b532bbfec6f5196 (plain)
  1. package com.example.portfolio3;
  2. // origin: <https://moodle.ruc.dk/course/section.php?id=211877>
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7. import java.util.Set;
  8. /// Adjecency Map Graph - A map from vertices
  9. /// to map of target vertex to edge
  10. class AdjMapGraph extends AbstractGraph {
  11. /// foo
  12. AdjMapGraph() { }
  13. /// foo
  14. private Map<Vertex, Map<Vertex, Edge>> outEdge = new HashMap<>();
  15. /// foo
  16. public void insertEdge(
  17. final Vertex v1, final Vertex v2, final int w
  18. ) {
  19. Edge e = new Edge(v1, v2, w);
  20. if (!outEdge.containsKey(e.from())) {
  21. outEdge.put(e.from(),
  22. new HashMap<Vertex, Edge>());
  23. }
  24. outEdge.get(e.from()).put(e.to(), e);
  25. }
  26. /// foo
  27. public Collection<Edge> edges() {
  28. Set<Edge> edges = new HashSet<>();
  29. for (Vertex v : outEdge.keySet()) {
  30. for (Vertex w : outEdge.get(v).keySet()) {
  31. edges.add(outEdge.get(v).get(w));
  32. }
  33. }
  34. return edges;
  35. }
  36. /// foo
  37. public Collection<Edge> outEdge(final Vertex v) {
  38. return outEdge.get(v).values();
  39. }
  40. /// foo
  41. public Integer getWeight(final Vertex v1, final Vertex v2) {
  42. // constant time operation
  43. if (!outEdge.containsKey(v1)) {
  44. return null;
  45. }
  46. if (!outEdge.get(v1).containsKey(v2)) {
  47. return null;
  48. }
  49. return outEdge.get(v1).get(v2).weight();
  50. }
  51. }