University-of-Washington-Navigator / src / main / java / pathfinder / WeightedGraph.java
WeightedGraph.java
Raw
package pathfinder;

import graph.Graph;
import graph.Node;
import pathfinder.datastructures.Path;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

// HERE TO MAKE TESTING FINDSHORTESTPATH EASY
public class WeightedGraph<E> extends Graph<E, Double> {
    /**
     * Finds the shortest path, by distance, between the two provided buildings.
     *
     * @param startPoint The short name of the building at the beginning of this path.
     * @param endPoint   The short name of the building at the end of this path.
     * @return A path between {@code startBuilding} and {@code endBuilding}, or {@literal null}
     * if none exists.
     * @throws IllegalArgumentException if {@code startBuilding} or {@code endBuilding} are
     *                                  {@literal null}, or not valid short names of buildings in
     *                                  this campus map.
     */
    public Path<E> findShortestPath(E startPoint, E endPoint) {
        PriorityQueue<Path<E>> active = new PriorityQueue<Path<E>>();
        Map<E, Path<E>> finished = new HashMap<E, Path<E>>();
        finished.put(startPoint, new Path<E>(startPoint));
        active.add(new Path<E>(startPoint));
        while (!active.isEmpty()) {
            Path<E> minPath = active.remove();
            E curPoint = minPath.getEnd();
            if (curPoint.equals(endPoint)) {
                return minPath;
            }
            finished.put(curPoint, minPath);
            Node<E, Double> curNode = getNode(curPoint);
            Map<Double, List<Node<E, Double>>> children = curNode.getEdges();
            for (double d : children.keySet()) {
                for (Node<E, Double> child : children.get(d)) {
                    if (!finished.containsKey(child.getName())) {
                        Path<E> newPath = minPath.extend(child.getName(), d);
                        if (!active.contains(newPath)) {
                            active.add(newPath);
                        }
                    }
                }
            }
        }
        return null;
    }

}