[prev] 12 [next]

Connected Components (cont)

Assign vertices to connected components:

int ncounted;      // # vertices allocated
int *componentOf;  // array of component ids
                   // indexed by vertex 0..V-1
void components(Graph g)
{
   int i, componentID = 1; 
   componentOf = calloc(nV(g),sizeof(int));
   ncounted = 0;
   while (ncounted < nV(g)) {
      Vertex v;
      for (v = 0; v < nV(g); v++)
         if (componentOf[v] == -1) break;
      dfsR(g, v, componentID);
      componentID++;
   }
   // componentOf[0..nV-1] is now set
}
void dfsR(Graph g, Vertex v, int c)
{
   componentOf[v] = c;
   ncounted++;
   Vertex w;
   for (w = 0; w < nV(g); w++) {
      if (!hasEdge(g,v,w)) continue;
      if (componentOf[w] == 0) dfsR(g,w,c);
   }
}