All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.stanford.nlp.graph.DijkstraShortestPath Maven / Gradle / Ivy

Go to download

Stanford CoreNLP provides a set of natural language analysis tools which can take raw English language text input and give the base forms of words, their parts of speech, whether they are names of companies, people, etc., normalize dates, times, and numeric quantities, mark up the structure of sentences in terms of phrases and word dependencies, and indicate which noun phrases refer to the same entities. It provides the foundational building blocks for higher level text understanding applications.

There is a newer version: 4.5.7
Show newest version
package edu.stanford.nlp.graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.stanford.nlp.util.BinaryHeapPriorityQueue;
import edu.stanford.nlp.util.Generics;

public class DijkstraShortestPath {
  private DijkstraShortestPath() {} // static method only

  public static  List getShortestPath(Graph graph,
                                               V node1, V node2, 
                                               boolean directionSensitive) {
    if (node1.equals(node2)) {
      return Collections.singletonList(node2);
    }

    Set visited = Generics.newHashSet();
    
    Map previous = Generics.newHashMap();
    
    BinaryHeapPriorityQueue unsettledNodes =
            new BinaryHeapPriorityQueue<>();

    unsettledNodes.add(node1, 0);

    while (unsettledNodes.size() > 0) {
      double distance = unsettledNodes.getPriority();
      V u = unsettledNodes.removeFirst();
      visited.add(u);

      if (u.equals(node2))
        break;

      unsettledNodes.remove(u);

      Set candidates = ((directionSensitive) ? 
                           graph.getChildren(u) : graph.getNeighbors(u));
      for (V candidate : candidates) {
        double alt = distance - 1;
        // nodes not already present will have a priority of -inf
        if (alt > unsettledNodes.getPriority(candidate) &&
            !visited.contains(candidate)) {
          unsettledNodes.relaxPriority(candidate, alt);
          previous.put(candidate, u);
        }
      }
    }
    if (!previous.containsKey(node2))
      return null;
    ArrayList path = new ArrayList<>();
    path.add(node2);
    V n = node2;
    while (previous.containsKey(n)) {
      path.add(previous.get(n));
      n = previous.get(n);
    }
    Collections.reverse(path);
    return path;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy