001 // GraphLab Project: http://graphlab.sharif.edu 002 // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology 003 // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/ 004 005 package graphlab.plugins.reports.basicreports; 006 007 import graphlab.graph.graph.GraphModel; 008 import graphlab.library.BaseGraph; 009 import graphlab.platform.lang.CommandAttitude; 010 import graphlab.plugins.main.GraphData; 011 import graphlab.plugins.main.core.AlgorithmUtils; 012 import graphlab.plugins.reports.extension.GraphReportExtension; 013 014 import java.util.ArrayList; 015 016 /** 017 * @author Mohammad Ali Rostami 018 */ 019 020 @CommandAttitude(name = "num_of_connected_components", abbreviation = "_nocc") 021 public class NumOfConnectedComponents implements GraphReportExtension { 022 023 public Object calculate(GraphData gd) { 024 GraphModel graph = gd.getGraph(); 025 return getNumOfConnectedComponents(graph); 026 } 027 028 /** 029 * @return Number of connected components of the given graph 030 */ 031 public static int getNumOfConnectedComponents(GraphModel graph) { 032 double[][] mat = graph.getAdjacencyMatrix().getArray(); 033 int size = mat.length; 034 ArrayList untraversed = new ArrayList(); 035 for (int i = 0; i < size; i++) 036 untraversed.add(new Integer(i)); 037 038 ArrayList comps = new ArrayList(); 039 int parent[] = new int[size]; 040 for (int i = 0; i < size; i++) 041 parent[i] = -1; 042 043 int cnt = 1; 044 ArrayList visit; 045 for (; untraversed.size() > 0; untraversed.removeAll(visit)) { 046 visit = new ArrayList(); 047 int currentNode = ((Integer) untraversed.get(0)).intValue(); 048 parent[currentNode] = currentNode; 049 AlgorithmUtils.dfs((BaseGraph) graph, currentNode, visit, parent); 050 comps.add(visit); 051 } 052 return comps.size(); 053 } 054 055 056 public String getName() { 057 return "Connected Components"; 058 } 059 060 public String getDescription() { 061 return "number of connected componentes"; 062 } 063 }