【核心代码】
int visited[maxSize];
void DFSTree(AGraph* G, int v, CSNode* T)
{
ArcNode* p;
int j;
int first = TRUE;
visited[v] = 1;
p = G->adjlist[v].firstarc;
CSNode* cs = NULL, *q = NULL;
while (p != NULL)
{
j = p->adjvex;
if (visited[j] == 0)
{
cs = (CSNode*)malloc(sizeof(CSNode));
cs->child = cs->sibling = NULL;
cs->data = G->adjlist[p->adjvex].data;
if (first)//为第一个孩子结点
{
T->child = cs;
first = FALSE;//易错:容易漏掉
}
else
{
q->sibling = cs;
}
q = cs;
DFSTree(G, j, q);
}
p = p->nextarc;
}
}
CSNode* DFSForest(AGraph* g)
{
CSNode* T = NULL;
CSNode* cs = NULL, *q = NULL;
int i;
for (i = 0; i < g->n; ++i)
{
visited[i] = FALSE;
}
for (i = 0; i < g->n; ++i)
{
if (visited[i] == FALSE)
{
cs = (CSNode*)malloc(sizeof(CSNode));
cs->child = cs->sibling = NULL;
cs->data = g->adjlist[i].data;
if (T == NULL)//易忘:不需要First了
T = cs;
else
q->sibling = cs;
q = cs;
DFSTree(g, i, q);
}
}
return T;
}
【验证代码】
#include <stdio.h>
#include <stdlib.h>
#define maxSize 100
#define TRUE 1
#define FALSE 0
typedef struct ArcNode
{
int adjvex;
struct ArcNode* nextarc;
}ArcNode;
typedef struct
{
char data;
ArcNode* firstarc;
}VNode;
typedef struct
{
VNode adjlist[maxSize];
int n, e;//顶点个数和边数
}AGraph;
typedef struct CSNode
{
char data;
struct CSNode* child, *sibling;
}CSNode;
void InsertEdge(AGraph* G, int v1, int v2)
{
ArcNode* p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = v2;
p->nextarc = G->adjlist[v1].firstarc;
G->adjlist[v1].firstarc = p;
/*无向图再加入下面一段代码*/
p = (ArcNode*)malloc(sizeof(ArcNode));//不可将p置空,因为要再新插入一个结点,必须给这个结点开辟一个空间
p->adjvex = v1;
p->nextarc = G->adjlist[v2].firstarc;
G->adjlist[v2].firstarc = p;
}
void CreateGraph(AGraph* G)
{
FILE* fp;
fp = fopen("Graph.dat", "r");
int nv, ne, i, v1, v2;
fscanf(fp,"%d%d", &nv, &ne);
for (i = 0; i < nv; i++)
{
G->adjlist[i].firstarc = NULL;
fscanf(fp, "%c", &G->adjlist[i].data);
}
for (i = 0; i < ne; ++i)
{
fscanf(fp,"%d%d", &v1, &v2);
InsertEdge(G, v1, v2);
}
G->e = ne;
G->n = nv;
}
int visited[maxSize];
void DFSTree(AGraph* G, int v, CSNode* T)
{
ArcNode* p;
int j;
int first = TRUE;
visited[v] = 1;
p = G->adjlist[v].firstarc;
CSNode* cs = NULL, *q = NULL;
while (p != NULL)
{
j = p->adjvex;
if (visited[j] == 0)
{
cs = (CSNode*)malloc(sizeof(CSNode));
cs->child = cs->sibling = NULL;
cs->data = G->adjlist[p->adjvex].data;
if (first)//为第一个孩子结点
{
T->child = cs;
first = FALSE;
}
else
{
q->sibling = cs;
}
q = cs;
DFSTree(G, j, q);
}
p = p->nextarc;
}
}
CSNode* DFSForest(AGraph* g)
{
CSNode* T = NULL;
CSNode* cs = NULL, *q = NULL;
int i;
for (i = 0; i < g->n; ++i)
{
visited[i] = FALSE;
}
for (i = 0; i < g->n; ++i)
{
if (visited[i] == FALSE)
{
cs = (CSNode*)malloc(sizeof(CSNode));
cs->child = cs->sibling = NULL;
cs->data = g->adjlist[i].data;
if (T == NULL)
T = cs;
else
q->sibling = cs;
q = cs;
DFSTree(g, i, q);
}
}
return T;
}
int main()
{
AGraph G;
CreateGraph(&G);
CSNode *T;
T = DFSForest(&G);
return 0;
}
关注我获取更多编程方面的知识,和我共同进步吧~