基于邻接表的图的建立与深度优先遍历

tech2023-01-06  98

#include <stdio.h> #include <stdlib.h> int visited[10]; //边表 typedef struct EdgeNode { int adjvex; struct EdgeNode *next; }EdgeNode; //顶点表 typedef struct VertexNode { int data; EdgeNode* firstedge; }VertexNode,VertexList[10]; typedef struct Graph { VertexList list; int numVertex; int numEdge; }Graph; void creatGraph(Graph *G) { int i; int j; int k; printf("请输入节点数和边数\n"); scanf_s("%d,%d", &G->numVertex, &G->numEdge); for (i = 0; i < G->numVertex; i++) { printf("请输入第%d个节点值", i); while (getchar() != '\n'); scanf_s("%d", &G->list[i].data); G->list[i].firstedge = NULL; } for (k = 0; k < G->numEdge; k++) { printf("请输入边的两个顶点序号:"); while (getchar() != '\n'); scanf_s("%d,%d", &i, &j); EdgeNode* e = (EdgeNode*)malloc(sizeof(EdgeNode)); e->adjvex = j; e->next = G->list[i].firstedge; G->list[i].firstedge = e; EdgeNode* q = (EdgeNode*)malloc(sizeof(EdgeNode)); q->adjvex = i; e->next = G->list[j].firstedge; G->list[j].firstedge = e; } } void DFS(Graph G, int i) { EdgeNode* p; visited[i] = 1; printf("%d", G.list[i].data); p = G.list[i].firstedge; while (p != NULL) { if (visited[p->adjvex] == 0) { DFS(G, p->adjvex); } p = p->next; } } void DFSTraverse(Graph G) { int i; for (i = 0; i < G.numVertex; i++) { visited[i] = 0; } for (i = 0; i < G.numVertex; i++) { if (visited[i] == 0) { DFS(G, i); } } } int main() { Graph G; creatGraph(&G); DFSTraverse(G); }
最新回复(0)