DFS生成森林代码
typedef char TElemType;
typedef struct CSNode{
TElemType data;
CSNode *firstChild, *nextSibling;
}CSNode,*CSTree;
void DFSForest(Graph G,CSTree &T)
{
T = NULL;
bool visited[MAXSIZE];
for(int i = 0; i < G.vexnum; i++)
visited[i] = false;
CSNode pre;
for(int v = 0; v < G.vexnum; v++)
{
if(!visited[v])
{
CSNode* p = (CSNode*)malloc(sizeof(CSNode));
*p = {getValue(G,v), NULL, NULL};
if(!T) T = p;
else pre->nextSibling = p;
pre = p;
DFSTree(G, v, p);
}
}
}
void DFSTree(Graph G, int v, CSTree &T)
{
visited[v] = true;
bool first = true;
CSNode *pre;
for(int w = FirstNeighbor(G, v); w >= 0; w = NextNeighbor(G, v, w))
{
if(!visited[w])
{
CSNode *p = (CSNode*)malloc(sizeof(CSNode));
*p = {getValue(G,w), NULL, NULL};
if(first)
{
T->firstChild = p; first = false;
}
else pre->nextSibling = p;
pre = p;
DFSTree(G,w,p);
}
}
}