blob: 8484d586a85543521c4907fcca0066f8dc32c678 (
plain)
- package com.example.portfolio3;
- // origin: <https://moodle.ruc.dk/course/section.php?id=211877>
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Map;
- import java.util.Set;
- /// Adjecency List Graph - A map from vertices to set of outedges from the vertex
- public class AdjListGraph extends AbstractGraph {
- /// foo
- public AdjListGraph() { }
- /// foo
- private Map<Vertex, Set<Edge>> outEdge = new HashMap<>();
- /// foo
- public final void insertEdge(final Vertex v1, final Vertex v2, final int w) {
- Edge e = new Edge(v1, v2, w);
- if (!outEdge.containsKey(e.from())) {
- outEdge.put(e.from(), new HashSet<Edge>());
- }
- outEdge.get(e.from()).add(e);
- }
- /// foo
- public final Collection<Edge> edges() {
- Set<Edge> edges = new HashSet<>();
- for (Vertex v: outEdge.keySet()) {
- edges.addAll(outEdge.get(v));
- }
- return edges;
- }
- /// foo
- public final Collection<Edge> outEdge(final Vertex v) {
- if (!outEdge.containsKey(v)) {
- return new HashSet<Edge>();
- }
- return outEdge.get(v);
- }
- /// foo
- public final Integer getWeight(final Vertex v1, final Vertex v2) {
- // linear in number of outedges from vertices
- if (!outEdge.containsKey(v1)) {
- return null;
- }
- for (Edge e: outEdge.get(v1)) {
- if (e.to() == v2) {
- return e.weight();
- }
- }
- return null;
- }
- }
|