数据结构之图的遍历BFS 邻接表+链栈

BFS需要用到队列,习惯了链栈,感觉链栈比较好写,循环队列以后再补吧。图的存储习惯用邻接表,虽然麻烦些,但是很好遍历。

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
#include <bits/stdc++.h>   //BFS 链栈 + 邻接表存图
using namespace std;
typedef struct Arcnode{
int vertex,data; //这条边的终点 以及权值
struct Arcnode *nextArc; //与这条边同起点的下一条边
}Arcnode;
typedef struct vernode{
int data; //顶点数据
Arcnode *nextArc; // 以该点为起点的边
}vernode;
typedef struct {
vernode vertex[1001];
int vernum,arcnum;
}Graph;
typedef struct Qnode{
int data;
struct Qnode *next;
}Qnode,*Qptr;
typedef struct {
Qptr front;
Qptr rear;
}Linkqueue;
int vis[1001];
int locate(Graph G, int x)
{
for(int i = 1 ; i <= G.vernum; ++i)
{
if(G.vertex[i].data == x)
{
return i;
}
}
}
void create(Graph &G)
{
int a,b,w;
cin >> G.vernum >> G.arcnum;
for(int i = 1; i <= G.vernum ; ++i)
{
cin >> G.vertex[i].data;
G.vertex[i].nextArc = NULL;
}
for(int i = 1; i <= G.arcnum; ++i)
{
cin >> a >> b >> w;
int A = locate(G,a);
int B = locate(G,b);
Arcnode *p,*p1;
p = new Arcnode; //!!!这一步总是忘记
p -> vertex = B;
p -> nextArc = G.vertex[A].nextArc;
p -> data = w;
G.vertex[A].nextArc = p;
p = new Arcnode;
p -> vertex = A;
p -> nextArc = G.vertex[B].nextArc;
p -> data = w;
G.vertex[B].nextArc = p;
}
}
void init(Linkqueue &Q)
{
Q.front = new Qnode;
Q.front -> next = NULL;
Q.rear = Q.front;
}
void push(Linkqueue &Q, int p)
{
Qnode *q;
q = new Qnode;
q -> data = p;
q -> next = NULL;
Q.rear -> next = q;
Q.rear = q;
}
int emptyqueue(Linkqueue Q)
{
if(Q.front == Q.rear)
return 1;
else
return 0;
}
void pop(Linkqueue &Q, int &p)
{
Qnode *q;
q = Q.front -> next;
p = q -> data;
Q.front -> next = q -> next;
if(q == Q.rear)
Q.rear = Q.front;
}
void bfs(Graph G,int v)
{
int p;
vis[v] = 1;
Linkqueue Q;
init(Q);
push(Q,v);
while(!emptyqueue(Q))
{
pop(Q,p);
cout << p << '\n';
Arcnode *q;
q = G.vertex[p].nextArc;
while(q != NULL)
{
if(!vis[q -> vertex])
{
vis[q -> vertex] = 1;
push(Q,q -> vertex);
}
q = q -> nextArc; //差点忘了这里
}
}
}
int main()
{
memset(vis,0,sizeof(vis));
Graph G;
create(G);
int v;
cin >> v;
bfs(G,v);
}