C++ 中的 class Graph
的构建及初始化
关于图的基本概念和图的存储结构可以参考 这篇帖子
1. 类构建
// 为方便起见不实行份文件编写
#include <map>
#include <set>
#include <utility>
class GraphNode;
class Edge {
public:
Edge(int weight, GraphNode * from, GraphNode * to) {
this->m_Weight = weight;
this->m_From = from;
this->m_To = to;
}
public:
int m_Weight; // 权值
GraphNode * m_From{
}; // 该边的出发点
GraphNode * m_To{
}; // 该边指向的点
};
class GraphNode {
public:
explicit GraphNode(int value, int in = 0, int out = 0) {
this->m_Value = value;
this->m_In = in;
this->m_Out = out;
}
public:
int m_Value; // 节点的值
int m_In; // 入度,指向该点的边的数量
int m_Out; // 出度,该点指向的点的数量
set<GraphNode *> m_NextNodesSet{
}; // 该点指向的点的集合
set<Edge *> m_EdgesSet{
}; // 由该点出发的边的集合
};
class Graph {
public:
~Graph() {
for (auto data : this->m_NodesMap) {
delete data.second;
}
for (auto edge : this->m_EdgesSet) {
delete edge;
}
}
public:
map<int, GraphNode *> m_NodesMap{
}; // (节点编号,节点)键值对,简单情况下可以用数组替代,加快寻址速度
set<Edge *> m_EdgesSet{
}; // 边的集合
};
2. 初始化方法举例
Graph * creatUndirectedGraph(