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

org.psjava.algo.graph.NumberOfConnectedComponents Maven / Gradle / Ivy

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