4-1 Strongly Connected Components (17分)
感想:
Write a program to find the strongly connected components in a digraph.
Format of functions:
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 intoStronglyConnectedComponents
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.
Sample program of judge:
#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 */
Sample Input (for the graph shown in the figure):
4 5
0 1
1 2
2 0
3 1
3 2
Sample Output:
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 isconect[15][15] = { 0 };
int i, j;
for (i = 0; i < G->NumOfVertices; i++) {
isconect[i][i] = 1;
int isread[15] = { 0 };
int t;
int stack[15];
t = 0;
stack[++t] = i;
while (t!=0) {
j = stack[t];
t--;
PtrToVNode b;
b = G->Array[j];
while (b != NULL) {
//b = b->Next;
isconect[i][b->Vert] = 1;
if (isread[b->Vert] == 0) {
isread[b->Vert] = 1;
stack[++t] = b->Vert;
}
b = b->Next;
}
}
}
int *a = (int*)malloc(G->NumOfVertices*(sizeof(int)));
for (i = 0; i < G->NumOfVertices ; i++)
a[i] = 0;
i = 0;
while (i < G->NumOfVertices) {
int j;
int fir = 0;
for (j = i; j < G->NumOfVertices; j++) {
if (isconect[i][j] == 1 && isconect[j][i] == 1) {
a[j] = 1;
if (fir == 0) {
fir = 1;
}
else
printf(" ");
(*visit)(j);
}
}
printf("\n");
while (a[i] != 0) {
i++;
if (i > G->NumOfVertices)
break;
}
}
}
感想:
坑点1虽然上面标了最大是10,但是测试用例的最大值却是15,2.图的邻接表储存第一个节点就是连接边而没有先存源节点值