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