本篇先用邻接矩阵示例。
假定图中有如下数据成员以及成员函数:
//邻接矩阵表示法
#ifndef GRAPH_H
#define GRAPH_H
#include "edge.h"
//template <typename T>
class Graph {
public:
using T = char;
...
void PrimMST(const int &index); //从点开始。
void KruskalMST(); //从边开始。
private:
const int& getWeight(const int &indexA, const int &indexB);
struct Vertex {
T data;
bool isVisited;
};
int capacity; //图中的顶点数
Vertex *pVertex; //顶点数组
int *pMatrix; //邻接矩阵
//边类,及边数组,为MST服务。将取出的边依次保存在pEdge中。
Edge *pEdge;
};
#endif
基本的建图、加点、加边、遍历,仅补充构造函数的实现,其余略过。
<span style="color:#800080;">
Graph</span><span style="color:#000000;">::</span><span style="color:#000000;">Graph</span><span style="color:#000000;">(</span><span style="color:#808000;">const</span><span style="color:#c0c0c0;"> </span><span style="color:#808000;">int</span><span style="color:#c0c0c0;"> </span><span style="color:#000000;">&</span><span style="color:#000000;">capacity</span><span style="color:#000000;">):</span><pre style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style="color:#c0c0c0;"> </span><span style="color:#800000;">capacity</span><span style