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 Parser processes raw text in English, Chinese, German, Arabic, and French, and extracts constituency parse trees.

There is a newer version: 3.9.2
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