aboutsummaryrefslogtreecommitdiff
path: root/src/com.example.portfolio3/com/example/portfolio3/AdjListGraph.java
blob: babaaaa748dbe1703825fea811e3030e27770500 (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 void insertEdge(Vertex v1,Vertex v2,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. outEdge.get(e.from()).add(e);
  20. }
  21. /// foo
  22. public Collection<Edge> edges(){
  23. Set<Edge> edges=new HashSet<>();
  24. for(Vertex v:outEdge.keySet())edges.addAll(outEdge.get(v));
  25. return edges;
  26. }
  27. /// foo
  28. public Collection<Edge> outEdge(Vertex v){
  29. if(!outEdge.containsKey(v))
  30. return new HashSet<Edge>();
  31. return outEdge.get(v);
  32. }
  33. /// foo
  34. public Integer getWeight(Vertex v1,Vertex v2){
  35. // linear in number of outedges from vertices
  36. if(!outEdge.containsKey(v1))return null;
  37. for(Edge e:outEdge.get(v1)){
  38. if(e.to()==v2)return e.weight();
  39. }
  40. return null;
  41. }
  42. }