采用邻接矩阵(或邻接表)实现图的遍历
(1)定义邻接矩阵(或邻接表)的存储结构;
(2)建立一个无向网G,如下图所示:
(3)对G进行深度优先遍历,结出结果;
(4)对G进行广度优先遍历,结出结果;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
#define INFINITY (int)1e9 //最大值无穷
#define MAX_VERTEX_NUM 20 //最大顶点个数
//(1)定义邻接矩阵的存储结构;
//由于示例只有权值,没有弧的其他信息,所以可以用int型矩阵表示
typedef enum { DG, DN, UDG, UDN }GraphKind;//{有向图,有向网,无向图,无向网}
typedef struct VNode {
int vexs[MAX_VERTEX_NUM];//顶点向量
int arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];//邻接矩阵
int vexnum, arcnum;//图的当前顶点数和弧数
GraphKind kind;//图的种类标志
}MGraph;
int vis[MAX_VERTEX_NUM];//标志数组
//(2)建立一个无向网G,如下图所示:
void CreateUDN(MGraph &G) {
printf("请输入图的当前顶点数、弧数:");
scanf("%d %d", &G.vexnum, &G.arcnum);
for (int i = 1; i <= G.vexnum; i++)//节点初始化
G.vexs[i] = i;
for (int i = 1; i <= G.vexnum; i++) {
for (int j = 1; j <= G.vexnum; j++)
//G.arcs[i][j] = INFINITY;
G.arcs[i][j] = 0;
}
printf("请输入弧数信息:\n");
for (int k = 0; k < G.arcnum; k++) {//每条边的权值
int v1, v2, w;
scanf("%d %d %d", &v1, &v2, &w);
G.arcs[v1][v2] = w;
G.arcs[v2][v1] = w;
}
}
void CreateGraph(MGraph &G) {
printf("\n请输入以数字 1 - n 为节点的图\n");
printf("请输入图的类型:\n");
printf("0.有向图\n");
printf("1.有向网\n");
printf("2.无向图\n");
printf("3.无向网\n");
scanf("%d", &G.kind);
switch (G.kind) {
//case DG: return CreateDG(G);//有向图
//case DN: return CreateDN(G);//有向网
// case UDG: return CreateUDG(G);//无向图
case UDN: return CreateUDN(G);//无向网
default: return;
}
}
//vis数组初始化
void init() {
for (int i = 0; i < MAX_VERTEX_NUM; i++)//标志数组初始化
vis[i] = 0;
}
//(3)对G进行深度优先遍历,结出结果;
void DFS(MGraph G, int v) {
//从第一个点开始
if (!vis[v]) {
printf("%d ", G.vexs[v]);
vis[v] = 1;
}
for (int i = 1; i <= G.vexnum; i++) {
if (G.arcs[v][i] != INFINITY && !vis[i])
DFS(G, i);
}
}
//(4)对G进行广度优先遍历,结出结果;
void BFS(MGraph G, int v) {
queue<int>Q;//建立队列
if (!vis[v]) {
printf("%d ", G.vexs[v]);
vis[v] = 1;
Q.push(v);
}
while (!Q.empty()) {
int vex;
vex = Q.front();
Q.pop();
for (int i = 1; i <= G.vexnum; i++) {
if (G.arcs[vex][i] != 0 && !vis[i]) {
printf("%d ", G.vexs[i]);
vis[i] = 1;
Q.push(i);
}
}
}
}
int main()
{
MGraph G;
CreateGraph(G);
printf("深度优先遍历:");
init();
DFS(G, 1);
printf("\n");
printf("广度优先遍历:");
init();
BFS(G, 1);
printf("\n");
system("pause");
return 0;
}
来源:CSDN
作者:qq_44939000
链接:https://blog.csdn.net/qq_44939000/article/details/103796209