#include <iostream>
#include <iomanip>
#define MAXVEX 100
using std::cout;
using std::cin;
using std::endl;
using std::setw;
struct ArcNode 
...{
int adjvex;
char info;
struct ArcNode *nextarc;
};
struct vexnode
...{
char data;
struct ArcNode *firstarc;
};
typedef struct vexnode AdjList[MAXVEX];
void creatbgraph(AdjList &g, int &n)
...{
int e, i, s, d;
struct ArcNode *p;
cout << "结点数(n)和边数(e):";
cin >> n >> e;
for (i = 0; i < n; i++)
...{
cout << "第" << i << "个结点信息:";
cin >> g[i].data;
g[i].firstarc = NULL;
}
for (int i = 0; i < e; i++)
...{
cout << "第" << setw(2) << i + 1 << "条边 起点序号,终点序号:";
cin >> s >> d;
p = new struct ArcNode;
p->adjvex = d;
p->info = g[d].data;
p->nextarc = g[s].firstarc;
g[s].firstarc = p;
}
}
void dispbgraph(AdjList &g, int n)
...{
int i;
struct ArcNode *p;
cout << "图的邻接表表示如下:" << endl;
for (i = 0; i < n; i++)
...{
cout << " [" << i << "," << g[i].data << "]: ";
p = g[i].firstarc;
while (p != NULL)
...{
cout << "(" << p->adjvex << "," << p->info << ") ->";
p = p->nextarc;
}
cout << "^" << endl;
}
}
int visited[MAXVEX];
void dfs(AdjList &adj, int v0)
...{
struct ArcNode *p;
visited[v0] = 2;
cout << v0 << " ";
p = adj[v0].firstarc;
while (p != NULL)
...{
if (visited[p->adjvex] == 0)
dfs(adj, p->adjvex);
p = p->nextarc;
}
}
int queue[MAXVEX], visit[MAXVEX];
void bfs(AdjList adj, int vi)
...{
int front = 0, rear = 0, v;
struct ArcNode *p;
visit[vi] = 1;
cout << vi << " ";
rear ++;
queue[rear] = vi;
while (front != rear)
...{
front = (front + 1) % MAXVEX;
v = queue[front];
p = adj[v].firstarc;
while (p != NULL)
...{
if (visit[p->adjvex] == 0)
...{
visit[p->adjvex] = 1;
cout << p->adjvex << " ";
rear = (rear + 1) % MAXVEX;
queue[rear] = p->adjvex;
}
p = p->nextarc;
}
}
}
int main()
...{
AdjList bgraph;
int n;
cout << "创建图如下 ";
creatbgraph(bgraph, n);
cout << "将图以邻接表的形式输出如下 ";
dispbgraph(bgraph, n);
int m;
cout << "请输入深度遍历图的起点: ";
cin >> m;
cout << "深度遍历顺序如下 ";
dfs(bgraph, m);
cout << ' ';
int p;
cout << "请输入广度遍历图的起点: ";
cin >> p;
cout << "广度遍历顺序如下 ";
bfs (bgraph, p);
cout << ' ';
}
本文介绍了一种使用邻接表表示图的数据结构,并通过C++实现深度优先搜索(DFS)和广度优先搜索(BFS)。展示了如何创建图、显示图的邻接表形式以及进行两种基本的图遍历。
946

被折叠的 条评论
为什么被折叠?



