4.4.3邻接表的广度优先遍历
程序员文章站
2022-05-22 10:06:39
...
#include <bits/stdc++.h>
#include "Graph.cpp"
using namespace std;
void BFS(ALGraph *G, int v) { // 邻接表的BFS算法
ArcNode *p;
int w;
int visited[MAXV];
queue<int> qu; // 定义存放访问过的顶点的标志数组
memset(visited, 0, sizeof(visited)); // 初始化访问标志数组
cout << v << " ";
visited[v] = 1;
qu.push(v); // 访问过的顶点进队
while(!qu.empty()) {
w = qu.front();
qu.pop(); // 出队顶点w
p = G->adjlist[w].firstarc; // 找到顶点w的第一个邻接点
while(p != NULL) {
if(visited[p->adjvex] == 0) {
cout << p->adjvex << " ";
visited[p->adjvex] = 1;
qu.push(p->adjvex);
}
p = p->nextarc; // 找到顶点w的下一个邻接点
}
}
cout << endl;
}
int main() {
ALGraph *G;
int A[][MAXV]= {
{0,1,0,0,1},
{0,0,1,1,1},
{0,0,0,0,0},
{0,0,1,0,1},
{0,0,0,0,0}
};
int n=5,e=7;
CreateAdj(G, A, n, e); //创建图的邻接表存储结构G
cout << "图的邻接表如下:" << endl;
DispAdj(G);
cout << "图的邻接表的广度优先遍历如下:" << endl;
BFS(G, 0);
return 0;
}
#include <bits/stdc++.h>
#define MAXV 50 // 最大顶点个数
#define MAXL 20
#define INF 0x3f3f3f3f //表示∞
using namespace std;
typedef struct ANode {
int adjvex; // 该边的终点编号
int weight; // 改变的权值
struct ANode *nextarc; //指向下一条边的指针
} ArcNode; // 边结点的类型
typedef struct Vnode {
char data[MAXL]; // 顶点信息
ArcNode *firstarc; // 指向第一条边
} VNode; // 邻接表的表头的结点类型
typedef VNode AdjList[MAXV]; // AdjList是邻接表类型
typedef struct {
AdjList adjlist; // 邻接表
int n, e; // 图中的顶点数和边数
} ALGraph; // 图
void CreateAdj(ALGraph *&G, int A[][MAXV], int n, int e) { //建立图的邻接表
ArcNode *p;
G = (ALGraph *) malloc (sizeof(ALGraph));
G->n = n;
G->e = e;
for(int k = 0; k < n; k++)
G->adjlist[k].firstarc = NULL;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(A[i][j] != 0 && A[i][j] != INF) {
p = (ArcNode *) malloc (sizeof(ArcNode));
p->adjvex = j;
p->weight = A[i][j];
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
}
}
void DispAdj(ALGraph *G) {
ArcNode *p;
for(int i = 0; i < G->n; i++) {
cout << i;
p = G->adjlist[i].firstarc;
while(p != NULL) {
cout << "->" << "结点编号:" << p->adjvex << " 边的权值:" << p->weight;
p = p->nextarc;
}
cout << "^" << endl;
}
}
void DestroyAdj(ALGraph *&G) { // 销毁图的邻接表
ArcNode * pre ,*p;
for(int i = 0; i < G->n; i++) {
pre = G->adjlist[i].firstarc;
while(pre != NULL) {
p = pre->nextarc;
free(pre);
pre = p;
}
}
free(G);
}