Write a program to find the strongly connected components in a digraph.
函数接口定义:
void StronglyConnectedComponents( Graph G, void (*visit)(Vertex V) );
where Graph is defined as the following:
typedef struct VNode *PtrToVNode;
struct VNode {
Vertex Vert;
PtrToVNode Next;
};
typedef struct GNode *Graph;
struct GNode {
int NumOfVertices;
int NumOfEdges;
PtrToVNode *Array;
};
Here void (*visit)(Vertex V) is a function parameter that is passed into StronglyConnectedComponents to handle (print with a certain format) each vertex that is visited. The function StronglyConnectedComponents is supposed to print a return after each component is found.
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define MaxVertices 10 /* maximum number of vertices */
typedef int Vertex; /* vertices are numbered from 0 to MaxVertices-1 */
typedef struct VNode *PtrToVNode;
struct VNode {
Vertex Vert;
PtrToVNode Next;
};
typedef struct GNode *Graph;
struct GNode {
int NumOfVertices;
int NumOfEdges;
PtrToVNode *Array;
};
Graph ReadG(); /* details omitted */
void PrintV( Vertex V )
{
printf("%d ", V);
}
void StronglyConnectedComponents( Graph G, void (*visit)(Vertex V) );
int main()
{
Graph G = ReadG();
StronglyConnectedComponents( G, PrintV );
return 0;
}
/* Your function will be put here */
输入样例:
4 5
0 1
1 2
2 0
3 1
3 2
输出样例:
3
1 2 0
Note: The output order does not matter. That is, a solution like
0 1 2
3
is also considered correct.
代码:
void StronglyConnectedComponents( Graph G, void (*visit)(Vertex V) )
{
int mp[MaxVertices][MaxVertices] = {0};//邻接矩阵
int num = G -> NumOfVertices;//顶点数
int vis[MaxVertices] = {0};
//将邻接表转换成邻接矩阵
for(int i = 0;i < num;i ++) {
PtrToVNode p = G -> Array[i];
while(p) {
mp[i][p -> Vert] = 1;//经过的顶点都标记一遍
p = p -> Next;
}
}
for(int k = 0;k < num;k ++) {
for(int i = 0;i < num;i ++) {
for(int j = 0;j < num;j ++) {
if(mp[i][k] && mp[k][j])
mp[i][j] = 1;// 如果存在 i->k->j 的路径,则标记 i->j 可达
}
}
}
for(int i = 0;i < num;i++)
{
if(vis[i]) continue;//如果顶点已经访问过,则跳过
visit(i);//访问当前顶点
vis[i] = 1;//标记当前顶点已访问
for(int j = 0;j < num;j ++) {
if(!vis[j] && mp[i][j] && mp[j][i]) {
vis[j] = 1;//标记与当前顶点同属一个强连通分量的顶点已访问
visit(j);//访问这些顶点
}
}
putchar('\n');//输出一个换行,表示一个强连通分量结束
}
}