#ifndef ALGRAPH_H #define ALGRAPH_H //领接表的存储结构 template struct ArcNode { E weight; int adjvex; ArcNode *nextarc; }; //顶点结点 template struct VexNode { V data; ArcNode *firstarc; }; //邻接表 template struct ALGraph { VexNode vexs[M]; int vexnum; int arcnum; bool visited[M]; }; //邻接表基本操作 // InitGraph(&G) template void InitGraph(ALGraph &G) { G.vexnum = 0; G.arcnum = 0; } // DestoryGraph(&G) template void DestoryGraph(ALGraph &G) { //释放所有弧结点 for (int v = 0; v < G.vexnum; v++){ auto p =G.vexs[v].firstarc; while (p) { // auto s = p -> nextarc; // delete p; // p = s; auto s = p; p = p ->nextarc; delete s; } } //顶点数、弧的数量置零 G.vexnum = 0; G.arcnum = 0; } // AddVertex(&G, vdata) template int AddVertex(ALGraph &G, V vdata) { if (G.vexnum == M) throw "Graph full"; int v = G.vexnum; G.vexs[v].data = vdata; G.vexs[v].firstarc = nullptr; G.vexnum++; // 顶点个数加 1 return v; // 返回新的顶点的编号 } //AddEdge(&G,s,t,e) template void AddEdge(ALGraph &G, int s, int t, E e) { if (s < 0 || s >= G.vexnum) throw "Invalid s"; if (t < 0 || t >= G.vexnum) throw "Invalid t"; auto p = new ArcNode; p -> adjvex = t; p -> weight = e; p -> nextarc = G.vexs[s].firstarc; G.vexs[s].firstarc = p; G.arcnum++; } #include // C++ 中的队列 // 从顶点 v 出发广度优先遍历图 G template void BFS(ALGraph &G, int v, F visit) { visit(G.vexs[v].data); G.visited[v] = true; std::queue q; // 定义一个队列,初始化为空 q.push(v); // 访问过的顶点入队列 while (!q.empty()) { int v = q.front(); q.pop(); // 出队列 // 遍历并访问 v 的未访问的邻接点 for (auto p = G.vexs[v].firstarc; p; p = p->nextarc) { int w = p->adjvex; // 邻接点的编号 w if (!G.visited[w]) { // 访问顶点 w visit(G.vexs[w].data); G.visited[w] = true; // w 入队列 q.push(w); } } } } //广度优先遍历图 G template void BFSTraverse(ALGraph &G, F visit) { for (int v= 0; v < G.vexnum; v++) G.visited[v] = false; for (int v = 0; v < G.vexnum; v++) if (!G.visited[v]) BFS(G, v, visit); } #endif