Strongly Connected Components
思路分析
使用tarjan
算法,求解强连通分量。
- 使用
DFS
后序遍历的过程中,对每一个节点V
:- 放入堆栈
Stack
; - 标记到达的时序
timeline
和可以返回到的最低时序back
; - 如果
V
的timeline
和back
相等,则说明此时堆栈顶到V
的部分是一个强连通分量,输出强连通分量部分。
- 放入堆栈
tarjan讲解
bilibili讲解:https://www.bilibili.com/video/BV19J411J7AZ?p=4&share_source=copy_web
调试
对于题目案例,我写出了相应的代码,附在结尾,可以根据这部分代码进行调试。
如果要测试其他案例数据,修改main()
函数中G
的值就可。
等效测试代码
#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();
Graph G = (Graph)malloc(sizeof(struct GNode));
G->NumOfEdges = 5;
G->NumOfVertices = 4;
G->Array = (PtrToVNode *)malloc(sizeof(struct VNode)*4);
G->Array[0] = (PtrToVNode)malloc(sizeof(struct VNode));
G->Array[0]->Vert = 1;
G->Array[0]->Next = NULL;
G->Array[1] = (PtrToVNode)malloc(sizeof(struct VNode));
G->Array[1]->Vert = 2;
G->Array[1]->Next = NULL;
G->Array[2] = (PtrToVNode)malloc(sizeof(struct VNode));
G->Array[2]->Vert = 0;
G->Array[2]->Next = NULL;
G->Array[3] = (PtrToVNode)malloc(sizeof(struct VNode));
G->Array[3]->Vert = 2;
G->Array[3]->Next = NULL;
G->Array[3]->Next = (PtrToVNode)malloc(sizeof(struct VNode));
G->Array[3]->Next->Vert = 1;
G->Array[3]->Next->Next = NULL;
StronglyConnectedComponents( G, PrintV );
return 0;
}
/* Your function will be put here */