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

edu.stanford.nlp.graph.ConnectedComponents 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.LinkedList;
import java.util.List;
import java.util.Set;

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

/**
 * Finds connected components in the graph, currently uses inefficient list for
 * variable 'verticesLeft'. It might give a problem for big graphs
 *
 * @author sonalg 08/08/11
 */
public class ConnectedComponents {

  public static  List> getConnectedComponents(Graph graph) {
    List> ccs = new ArrayList<>();
    LinkedList todo = new LinkedList<>();
    // TODO: why not a set?
    List verticesLeft = CollectionUtils.toList(graph.getAllVertices());
    while (verticesLeft.size() > 0) {
      todo.add(verticesLeft.get(0));
      verticesLeft.remove(0);
      ccs.add(bfs(todo, graph, verticesLeft));
    }
    return ccs;
  }

  private static  Set bfs(LinkedList todo, Graph graph, List verticesLeft) {
    Set cc = Generics.newHashSet();
    while (todo.size() > 0) {
      V node = todo.removeFirst();
      cc.add(node);
      for (V neighbor : graph.getNeighbors(node)) {
        if (verticesLeft.contains(neighbor)) {
          cc.add(neighbor);
          todo.add(neighbor);
          verticesLeft.remove(neighbor);
        }
      }
    }

    return cc;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy