-
Notifications
You must be signed in to change notification settings - Fork 0
/
AdjList.cpp
158 lines (145 loc) · 3.01 KB
/
AdjList.cpp
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <iostream>
#define MAXSIZE 50
using namespace std;
/*存放边*/
typedef struct ArcNode
{
int adjVertex;//
struct ArcNode* nextArc;
} ANode;
/*存放点*/
typedef struct VertexNode
{
char data;
struct ArcNode* firstArc;
} VNode;
/*邻接表*/
typedef struct Graph
{
VNode vertex[MAXSIZE];
int vn, en;
} Graph;
bool visited[MAXSIZE];
void createGraph(Graph &G);
void DFSTraverse(Graph &G);
void DFS(Graph &G, int start);
void BFSTraverse(Graph &G);
void BFS(Graph &G, int start);
int main()
{
Graph G;
createGraph(G);
BFSTraverse(G);
return 0;
}
void createGraph(Graph &G)
{
int v1, v2;
ANode* p = NULL;
cout << "请输入点数:";
cin >> G.vn;
cout << "请输入边数:";
cin >> G.en;
/*初始化所有顶点*/
cout << "请依次输入顶点的数据:";
for (int i = 0; i < G.vn; i++)
{
cin >> G.vertex[i].data;
G.vertex[i].firstArc = NULL;
}
/*构造边的关系*/
for (int i = 0; i < G.en; i++)
{
cout << "请输入边(用两点表示):";
cin >> v1 >> v2;//0 1
p = new ANode;
p->adjVertex = v2;
p->nextArc = G.vertex[v1].firstArc;
G.vertex[v1].firstArc = p;
p = new ANode;
p->adjVertex = v1;
p->nextArc = G.vertex[v2].firstArc;
G.vertex[v2].firstArc = p;
}
cout << endl;
// for(int i=0; i<G.vn; i++)
// {
// cout << "vertex" << i << "的边是:";
// p = G.vertex[i].firstArc;
// while(p)
// {
// cout << p->adjVertex << " ";
// p = p->nextArc;
// }
// cout << endl;
// }
}
void DFSTraverse(Graph &G)
{
for (int i = 0; i < G.vn; i++)
{
visited[i] = false;
}
for (int i = 0; i < G.vn; i++)
{
if (visited[i] == false)
{
DFS(G, i);
}
}
}
void DFS(Graph &G, int start)
{
cout << G.vertex[start].data << " ";
visited[start] = true;
ANode* p = G.vertex[start].firstArc;
while (p)
{
if (visited[p->adjVertex] == false)
{
DFS(G, p->adjVertex);
}
p = p->nextArc;
}
}
void BFSTraverse(Graph &G)
{
for (int i = 0; i < G.vn; i++)
{
visited[i] = false;
}
for (int i = 0; i < G.vn; i++)
{
if (visited[i] == false)
{
BFS(G, i);
}
}
}
void BFS(Graph &G, int start)
{
ANode* p = NULL;
int queue[G.vn + 1];
int front, rear, i, j;
front = rear = 0;
queue[++rear] = start;
cout << G.vertex[start].data << " ";
visited[start] = true;
while (rear != front)
{
i = queue[++front];
p = G.vertex[i].firstArc;
//入队
while(p)
{
i = p->adjVertex;
if (visited[i] == false)
{
cout << G.vertex[i].data << " ";
queue[++rear] = i;
visited[i] = true;
}
p = p->nextArc;
}
}
}