org.psjava.algo.graph.NumberOfConnectedComponents Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of psjava Show documentation
Show all versions of psjava Show documentation
Problem Solving Library for Java
The newest version!
package org.psjava.algo.graph;
import org.psjava.ds.graph.AllEdgeInGraph;
import org.psjava.ds.graph.Graph;
import org.psjava.ds.graph.UndirectedEdge;
import org.psjava.ds.set.DisjointSet;
import org.psjava.ds.set.MutableSet;
import org.psjava.goods.GoodDisjointSet;
import org.psjava.goods.GoodMutableSetFactory;
public class NumberOfConnectedComponents {
public static > int calc(Graph graph) {
DisjointSet dset = GoodDisjointSet.create();
for (V v : graph.getVertices())
dset.makeSet(v);
for (E e : AllEdgeInGraph.wrap(graph))
dset.union(e.v1(), e.v2());
MutableSet finalReps = GoodMutableSetFactory.getInstance().create();
for (V v : graph.getVertices())
finalReps.addIfAbsent(dset.find(v));
return finalReps.size();
}
private NumberOfConnectedComponents() {
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy