解题思路:
尝试写了出来。
参考代码:
#include<stdio.h> #include<malloc.h> #define MAX_VEX_NUM 50 #define True 1 #define False 0 typedef struct AdjCell{ int adj; //int *info; } AdjCell, AdjMatrix[MAX_VEX_NUM][MAX_VEX_NUM]; typedef struct MGraph{ int vexs[MAX_VEX_NUM]; AdjMatrix arcs; int vexnum; //int arcnum; } MGraph; typedef struct CSNode{ int data; struct CSNode *firstchild; struct CSNode *nextsibling; } *CSTree, CSNode; void CreateMGraph(MGraph *G); void DFSForest(MGraph *G, CSTree *T); void DFSTree(MGraph *G, CSTree *T, int i, int *visited); void PreOrderTraverse(CSTree T); int main() { MGraph G; CSTree T = NULL; CreateMGraph(&G); DFSForest(&G, &T); return 0; } void CreateMGraph(MGraph *G){ int i, j; scanf("%d", &G->vexnum); for(i = 0; i < G->vexnum; i++){ G->vexs[i] = i; } for(i = 0; i < G->vexnum; i++){ for(j = 0; j < G->vexnum; j++){ scanf("%d", &G->arcs[i][j].adj); } } } void DFSForest(MGraph *G, CSTree *T){ int visited[MAX_VEX_NUM] = { False }; int i; CSNode *p = NULL, *q = NULL; for(i = 0; i < G->vexnum; i++){ if(visited[i] == False){ p = (CSNode *)malloc(sizeof(CSNode)); p->data = G->vexs[i]; p->firstchild = NULL; p->nextsibling = NULL; if(!(*T)){ (*T) = p; } else{ q->nextsibling = p; } q = p; DFSTree(G, &p, i, visited); PreOrderTraverse(p); } } } void DFSTree(MGraph *G, CSTree *T, int i, int *visited){ visited[i] = True; int j, first = True; CSNode *p = NULL, *q = NULL; for(j = 0; j < G->vexnum; j++){ if(G->arcs[i][j].adj == 1 && visited[j] == False){ p = (CSNode *)malloc(sizeof(CSNode)); p->data = j; p->firstchild = NULL; p->nextsibling = NULL; if(first == True){ (*T)->firstchild = p; first = False; } else{ q->nextsibling = p; } q = p; DFSTree(G, &p, j, visited); } } } void PreOrderTraverse(CSTree T){ CSNode *stack[MAX_VEX_NUM]; int top = -1; CSNode *p = T; while(p || top > -1){ if(p){ printf("%d ", p->data); stack[++top] = p; p = p->firstchild; } else{ p = stack[top--]; p = p->nextsibling; } } printf("\n"); }
0.0分
5 人评分
回文串 (C语言代码)浏览:2845 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:640 |
【偶数求和】 (C语言代码)浏览:556 |
WU-判定字符位置 (C++代码)浏览:1395 |
DNA (C语言代码)浏览:540 |
C语言程序设计教程(第三版)课后习题5.6 (C语言代码)浏览:901 |
数对 (C语言代码)浏览:697 |
A+B for Input-Output Practice (VI) (C语言代码)浏览:552 |
Tom数 (C语言代码)浏览:724 |
C语言程序设计教程(第三版)课后习题6.8 (C语言代码)浏览:650 |