Strongly Connected Component Algorithm
Code :
#include<stdio.h>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX 100
vector<int>vcc[MAX],vcc1[MAX],collect;
int vertex ,edge,color[MAX];
void topsort(int n)
{
color[n]=1;
int i;
for(i=0; i<vcc[n].size(); i++)
{
if(color[vcc[n][i]]==0)
{
topsort(vcc[n][i]);
}
}
collect.push_back(n);
}
void dfs(int n)
{
color[n]=1;
int i;
for(i=0; i<vcc1[n].size(); i++)
{
if(color[vcc1[n][i]]==0)
{
printf("->%d",vcc1[n][i]);
dfs(vcc1[n][i]);
}
}
}
int main()
{
int i,j,k,len,n,m;
scanf("%d %d",&vertex,&edge);
for(i=1; i<=edge; i++)
{
scanf("%d %d",&n,&m);
vcc[n].push_back(m);
vcc1[m].push_back(n);
}
for(i=1; i<=vertex; i++)
{
if(color[i]==0)
{
topsort(i);
}
}
std::reverse(collect.begin(), collect.end());
memset(color,0,sizeof(color));
int cou =0;
printf("Strongly connected path : \n");
for(i=0; i<collect.size(); i++)
{
if(color[collect[i]]==0)
{
cou++;
printf("%d",collect[i]);
dfs(collect[i]);
printf("\n");
}
}
printf("\n%d strongly connected component found\n",cou);
}
No comments:
Post a Comment