#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 09:34:25 浏览: 173
这段代码是一个图的创建和遍历的程序,使用的是邻接表来存储图的信息。具体来说,这里定义了三个结构体:Node、ENode和GNode。其中,Node表示邻接表中的一个节点,ENode表示一个顶点和其邻接表组成的一个节点,GNode表示整个图。程序中先通过createGraph()函数创建了一个图,并将其存储在GNode中。在createGraph()函数中,先读入了顶点个数和边的个数,然后再读入每个顶点的数据,并将其存储在ENode中。接着,读入每条边的起始点、终止点和权重,并将其存储在邻接表中。最后,程序分别调用了DFSTraverse()和BFSTraverse()函数对图进行深度优先遍历和广度优先遍历,并输出结果。
阅读全文