#include <iostream> #include <queue> using namespace std; const int VEX_MAX = 100; bool visited[VEX_MAX]; struct Node { int vex; int weight; struct Node* next; }; typedef struct ENode { char data; Node* head; }*List; typedef struct GNode { List list; int vexnum; int arcnum; }*Graph; Graph createGraph(); void DFSTraverse(Graph graph); void DFS(Graph graph, int v); void BFSTraverse(Graph graph); void printGraph(Graph graph); int main() { Graph graph = createGraph(); printGraph(graph); cout << "深度优先遍历:" << endl; DFSTraverse(graph); cout << endl; cout << "广度优先遍历:" << endl; BFSTraverse(graph); return 0; } Graph createGraph() { Graph graph = new GNode; cout << "请输入顶点个数和边个数:" << endl; cin >> graph->vexnum >> graph->arcnum; graph->list = new ENode[graph->vexnum + 1]; cout << "请输入顶点数据:" << endl; for (int i = 1; i <= graph->vexnum; i++) { cin >> graph->list[i].data; graph->list[i].head = NULL; } int begin, end, weight; cout << "请输入边的起始点及其权重:" << endl; for (int i = 1; i <= graph->arcnum; i++) { cin >> begin >> end >> weight; Node* node = new Node; node->weight = weight; node->vex = end; node->next = graph->list[begin].head; graph->list[begin].head = node; node = new Node; node->weight = weight; node->vex = begin; node->next = graph->list[end].head; graph->list[end].head = node; } return graph; }讲解
时间: 2024-04-05 19:34:25 浏览: 15
这段代码是一个图的创建和遍历的程序,使用的是邻接表来存储图的信息。具体来说,这里定义了三个结构体:Node、ENode和GNode。其中,Node表示邻接表中的一个节点,ENode表示一个顶点和其邻接表组成的一个节点,GNode表示整个图。程序中先通过createGraph()函数创建了一个图,并将其存储在GNode中。在createGraph()函数中,先读入了顶点个数和边的个数,然后再读入每个顶点的数据,并将其存储在ENode中。接着,读入每条边的起始点、终止点和权重,并将其存储在邻接表中。最后,程序分别调用了DFSTraverse()和BFSTraverse()函数对图进行深度优先遍历和广度优先遍历,并输出结果。
相关问题
#include <iostream> #include<algorithm> #include<cmath> #include <queue> using namespace std;
#include <iostream>:这是C++标准库中的头文件,用于输入输出流操作,包括cin、cout等。
#include<algorithm>:这是C++标准库中的头文件,用于提供各种算法操作,如排序、查找等。
#include<cmath>:这是C++标准库中的头文件,用于提供数学函数操作,如绝对值、平方根等。
#include <queue>:这是C++标准库中的头文件,用于提供队列操作,包括入队、出队等。
using namespace std;:这是C++的命名空间声明,表示使用std命名空间,可以直接使用std中的函数和对象。
#include <iostream> #include <queue> #include <string> using namespace std;对代码进行注释
代码注释如下:
```c++
#include <iostream> // 引入输入输出流库
#include <queue> // 引入队列库
#include <string> // 引入字符串库
using namespace std; // 使用 std 命名空间
// 主函数
int main() {
queue<string> q; // 定义一个字符串队列 q
// 往队列中添加元素
q.push("apple");
q.push("banana");
q.push("orange");
// 输出队列头部元素
cout << q.front() << endl; // 输出:apple
// 弹出队列头部元素
q.pop();
// 输出队列头部元素
cout << q.front() << endl; // 输出:banana
// 输出队列中元素的个数
cout << "The size of the queue is " << q.size() << endl; // 输出:The size of the queue is 2
return 0; // 返回 0 表示程序正常结束
}
```