1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #define N 100 char letter[26] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z' }; struct ArcNode { struct ArcNode* next; int vertex; }; struct verNode { int vertex; struct ArcNode* first; }; struct Stack { int top=-1; int a[N]; }; void Initial(int n); void crtGraph(int ver, int arc); void dfs_travel(int n); void dfs(int i); void push(int data); int pop(); struct verNode Ver[N]; int visited[N]; struct Stack newStack; int main(void) {
int n, e; int ver, arc; scanf("%d %d", &n, &e); Initial(n); for (int i = 0; i < e; i++) { scanf("%d %d", &ver, &arc); crtGraph(ver, arc); } dfs_travel(n); while (newStack.top!=-1) { int i = pop(); printf("%c ", letter[i]); }
return 0; } void Initial(int n) { for (int i = 0; i < n; i++) { Ver[i].first = NULL; Ver[i].vertex = i; } } void crtGraph(int ver, int arc) { struct ArcNode* q = (struct ArcNode*)malloc(sizeof(struct ArcNode)); q->vertex = arc; q->next = NULL; if (Ver[ver].first == NULL) Ver[ver].first = q; else { struct ArcNode* pTemp = Ver[ver].first; while (pTemp->next != NULL) { pTemp = pTemp->next; } pTemp->next = q; } } void dfs_travel(int n) { for (int i = 0; i < n; i++) { if (!visited[i]) dfs(i); } } void dfs(int i) { visited[i] = 1; struct ArcNode* p = Ver[i].first; while (p != NULL) { if (!visited[p->vertex]) { dfs(p->vertex); } p = p->next; } push(i); } void push(int data) { newStack.a[++newStack.top] = data; } int pop() { return newStack.a[newStack.top--]; }
|