aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/AdjListGraph.java
blob: 8484d586a85543521c4907fcca0066f8dc32c678 (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 List Graph - A map from vertices to set of outedges from the vertex
  9. public class AdjListGraph extends AbstractGraph {
  10. /// foo
  11. public AdjListGraph() { }
  12. /// foo
  13. private Map<Vertex, Set<Edge>> outEdge = new HashMap<>();
  14. /// foo
  15. public final void insertEdge(final Vertex v1, final Vertex v2, final int w) {
  16. Edge e = new Edge(v1, v2, w);
  17. if (!outEdge.containsKey(e.from())) {
  18. outEdge.put(e.from(), new HashSet<Edge>());
  19. }
  20. outEdge.get(e.from()).add(e);
  21. }
  22. /// foo
  23. public final Collection<Edge> edges() {
  24. Set<Edge> edges = new HashSet<>();
  25. for (Vertex v: outEdge.keySet()) {
  26. edges.addAll(outEdge.get(v));
  27. }
  28. return edges;
  29. }
  30. /// foo
  31. public final Collection<Edge> outEdge(final Vertex v) {
  32. if (!outEdge.containsKey(v)) {
  33. return new HashSet<Edge>();
  34. }
  35. return outEdge.get(v);
  36. }
  37. /// foo
  38. public final Integer getWeight(final Vertex v1, final Vertex v2) {
  39. // linear in number of outedges from vertices
  40. if (!outEdge.containsKey(v1)) {
  41. return null;
  42. }
  43. for (Edge e: outEdge.get(v1)) {
  44. if (e.to() == v2) {
  45. return e.weight();
  46. }
  47. }
  48. return null;
  49. }
  50. }