-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.c
89 lines (75 loc) · 1.6 KB
/
Graph.c
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
86
87
88
89
#include <stdio.h>
#define MaxSize 50
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
int info;
}ArcNode;
typedef struct VNode{
char data;
ArcNode *firstarc;
}VNode;
typedef struct{
VNode adjlist[MaxSize];
int n, e;
}AGraph;
int visit[MaxSize];
void CreateGraphAL(AGraph *G)
{
int i, j, k;
ArcNode *s;
printf("请输入顶点数和边数(输入格式为:顶点数,边数):\n");
scanf("%d %d", &(G->n), &(G->e));
getchar();
printf("请输入顶点信息(输入格式为:顶点号<CR>)每个顶点以回车作为结束: \n");
for(i = 0; i < G->n; ++i)
{
scanf("%c", &(G->adjlist[i].data));
getchar();
G->adjlist[i].firstarc = NULL;
}
printf("请输入边的信息(输入格式为:i,j):\n");
for(k = 0;k < G->e; k++)
{
scanf("%d, %d", &i, &j);
s = (ArcNode *)malloc(sizeof(ArcNode));
s->adjvex = j;
s->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = s;
s = (ArcNode *)malloc(sizeof(ArcNode));
s->adjvex = i;
s->nextarc = G->adjlist[j].firstarc;
G->adjlist[j].firstarc = s;
}
}
void Visit(char a)
{
printf("%c\n", a);
}
void DFS(AGraph *G, int v)
{
ArcNode *p = G->adjlist[v].firstarc;
visit[v] = 1;
//Visit(v);
Visit(G->adjlist[v].data);
while(p != NULL)
{
if(visit[p->adjvex] == 0)
DFS(G, p->adjvex);
p = p->nextarc;
}
}
void DFSTraverse(AGraph *G)
{
int i;
for(i = 0; i < G->n; ++i)
if(!visit[i])
DFS(G, i);
}
int main()
{
AGraph G;
CreateGraphAL(&G);
DFSTraverse(&G);
return 0;
}