package it.univr.di.cstnu.util; import it.unimi.dsi.fastutil.objects.*; import it.univr.di.cstnu.graph.LabeledNode; import it.univr.di.labeledvalue.Constants; import javax.annotation.Nonnull; /** * Implementation based on two nested hash maps. */ public class GraphDistancesImpl implements GraphDistances { /** * Maintains the distances from a node to each reachable node. */ private final Object2ObjectMap> distancesMatrix; /** * Default constructor */ public GraphDistancesImpl() { distancesMatrix = new Object2ObjectOpenHashMap<>(); } /** * */ @Override public int getDistance(@Nonnull LabeledNode source, @Nonnull LabeledNode destination) { final Object2IntMap subMap = distancesMatrix.get(source); if (subMap == null) { return Constants.INT_POS_INFINITE; } return subMap.getInt(destination); } /** * */ @Override public ObjectSet getNodes() { ObjectSet list = new ObjectArraySet<>(); if (distancesMatrix.size() > 0) { list = distancesMatrix.keySet(); } return list; } /** * */ @Override public Object2IntMap getReachable(@Nonnull LabeledNode node) { final Object2IntMap subMap = distancesMatrix.get(node); if (subMap == null) { return new Object2IntOpenHashMap<>(); } return subMap; } /** * */ @Override public void putDistance(@Nonnull LabeledNode source, @Nonnull LabeledNode destination, int distance) { Object2IntMap subMap = distancesMatrix.get(source); if (subMap == null) { subMap = new Object2IntOpenHashMap<>(); subMap.defaultReturnValue(Constants.INT_POS_INFINITE); distancesMatrix.put(source, subMap); } subMap.put(destination, distance); } /** * */ @Override public void putDistances(@Nonnull LabeledNode source, @Nonnull Object2IntMap destinations) { destinations.defaultReturnValue(Constants.INT_POS_INFINITE); distancesMatrix.put(source, destinations); } /** * */ @Override public void removeDistance(@Nonnull LabeledNode source, @Nonnull LabeledNode destination) { final Object2IntMap subMap = distancesMatrix.get(source); if (subMap == null) { return; } subMap.removeInt(destination); } /* * @return a string representation ordered by the node's natural order. */ @Override public String toString() { final Object2ObjectSortedMap> orderedMap = new Object2ObjectAVLTreeMap<>(distancesMatrix); final StringBuilder sb = new StringBuilder(80); sb.append("{").append("\n"); for (final LabeledNode node : orderedMap.keySet()) { final Object2IntSortedMap subMap = new Object2IntAVLTreeMap<>(orderedMap.get(node)); sb.append(node).append(" -> ").append(subMap).append("\n"); } sb.append("}"); return sb.toString(); } }