有向图的深度/广度优先遍历算法
// 鄰接表存儲與廣度和深度優先算法
#include <iostream>?
using namespace std;
#define MAX_VERTEX_NUM 100
typedef enum {
?DG,DN,UDG,UDN
}GraphKind;
typedef struct EdgeNode {
?int adjvex; // 存儲鄰接點在頂點中的位置
?struct EdgeNode *nextedge;
?int weight;
}EdgeNode;
typedef struct VexNode {
?char vex;
?EdgeNode *firstedge;
}VexNode;
?
typedef struct {
?VexNode vexs[MAX_VERTEX_NUM];
?int vexnum, edgenum;
?GraphKind kind;
}LGraph;
// 構造有向圖的鄰接表,頂點數n,邊數 e
void CreateDG(LGraph &G, int n, int e) {
?char ch;
?int i, j;
?G.vexnum = n;
?G.edgenum = e;
?// 頂點信息初始化
?for (i = 0; i < n; i++) {
??cin >> ch;
??G.vexs[i].vex = ch;
??G.vexs[i].firstedge = NULL;
?}
?// 邊的信息初始化
?for (int k = 0; k < e; k++) {
??cin >> i >> j;
??EdgeNode *p = new EdgeNode;
??p->adjvex = j;
??p->nextedge = G.vexs[i].firstedge;
??G.vexs[i].firstedge = p; // 采用頭插法來構建
?}
}
// 有向圖的深度優先算法
int visited[MAX_VERTEX_NUM];
void DFS(LGraph &G, int i) {
?visited[i] = 1;
?cout << G.vexs[i].vex << " ";
?int j; // 當前訪問的節點信息
?EdgeNode *p;
?p = G.vexs[i].firstedge;
?while (p) {
??j = p->adjvex;
??if (!visited[j]) {
???DFS(G, j);
??}
??p = p->nextedge;
?}
}
void DFS_Traverse(LGraph &G) {
?for (int i = 0; i < G.vexnum; i++) {
??visited[i] = 0;
?}
?for (int i = 0; i < G.vexnum; i++) {
??if (!visited[i]) {
???DFS(G, i);
??}
?}
}
//? 有向圖的廣度優先遍歷
const int Queue_Size = 100;
typedef struct circlQueue {
?int *elem;
?int front, rear;
?int queueSize;
}circlQueue;
// 循環隊列初始化
void init_circleQueue(circlQueue &Q) {
?Q.elem = new int[Queue_Size];
?Q.front = Q.rear = 0;
?Q.queueSize = Queue_Size;
}
// 入隊列
void enterQueue(circlQueue &Q, int x) {
?// 判滿
?if ((Q.rear + 1)%Q.queueSize == Q.front) {
??cout << "Queue OverFlow!" << endl;
?}
?Q.elem[Q.rear] = x;
?Q.rear = (Q.rear + 1) % Q.queueSize;
}
// 出隊列
void outQueue(circlQueue &Q, int &e) {
?// 判空
?if (Q.front == Q.rear) {
??cout << "Queue Empty!" << endl;
?}
?e = Q.elem[Q.front];
?Q.front = (Q.front + 1) % Q.queueSize;
}
// 廣度優先
void BFS_Traverse(LGraph &G) {
?for (int i = 0; i < G.vexnum; i++)
??visited[i] = 0;
?circlQueue Q;
?init_circleQueue(Q);
?int v1,v2;
?for (int i = 0; i < G.vexnum; i++) {
??if (!visited[i]) {
???visited[i] = 1;
???cout << G.vexs[i].vex << " ";
???enterQueue(Q, i);
???// 隊列不空
???while (Q.rear != Q.front) {
????outQueue(Q, v1);
????EdgeNode *p;
????p = G.vexs[v1].firstedge;
????while(p){
?????v2 = p->adjvex;
?????if (!visited[v2]) {
??????cout << G.vexs[v2].vex << " ";
??????visited[v2] = 1;
??????enterQueue(Q, v2);
?????}
?????p = p->nextedge;
????}
???}
??}
?}
}
int main() {
?LGraph G;
?int n, e;
?cout << "請輸入頂點數目:" << endl;
?cin >> n;
?cout << "請輸入邊的數目:" << endl;
?cin >> e;
?CreateDG(G, n, e);
?cout << "深度優先搜索結果:" << endl;
?DFS_Traverse(G);
?cout << endl;
?cout << "廣度優先搜索結果:" << endl;
?BFS_Traverse(G);
?system("pause");
?return 0;
}
轉載于:https://www.cnblogs.com/codingtao/p/6430429.html
總結
以上是生活随笔為你收集整理的有向图的深度/广度优先遍历算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codis集群的搭建与使用
- 下一篇: 控制台执行CI方法