实现基于邻接表表示的广度优先遍历。
函数接口定义:
void BFS(ALGraph G, int v);
void DFS(ALGraph G, int v);
其中 G
是基于邻接表存储表示的无向图,v
表示遍历起点。
输入样例:
输入第1行为结点数vexnum和边数arcnum。第2行为结点的值,依次输入arcnum行,每行输入两个结点的值表示该两个结点互为邻接点。
8 8
ABCDEFGH
A B
A C
B D
B E
C F
C G
D H
E H
输出样例:
遍历序列。
A C B G F E D H
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
BFS:
#include<iostream>
#include<queue>
using namespace std;
queue<int> q;
void BFS(ALGraph G, int v) {
visited[v] = 1;
q.push(v);
while (!q.empty()) {
int tmp = q.front();
q.pop();
cout << G.vertices[tmp].data << " ";
ArcNode* x = G.vertices[tmp].firstarc;
while (x) {
if (!visited[x->adjvex]) {
q.push(x->adjvex);
visited[x->adjvex] = 1;
}
x = x->nextarc;
}
}
}
DFS:
#include<iostream>
void DFS(ALGraph G, int v) {
visited[v] = 1;
std::cout << G.vertices[v].data << " ";
ArcNode* tmp = G.vertices[v].firstarc;
while (tmp) {
if (!visited[tmp->adjvex]) DFS(G, tmp->adjvex);
tmp = tmp->nextarc;
}
}