Update graph codes

This commit is contained in:
krahets
2023-02-15 03:35:54 +08:00
parent 5541fe5964
commit 8e0080f003
6 changed files with 29 additions and 90 deletions

View File

@ -14,8 +14,9 @@ struct Vertex {
/* 基于邻接表实现的无向图类 */
class GraphAdjList {
// 请注意vertices 和 adjList 中存储的都是 Vertex 对象
unordered_map<Vertex*, unordered_set<Vertex*>> adjList; // 邻接表(使用哈希表实现)
// 邻接表,使用哈希表来代替链表,以提升删除边、删除顶点的效率
// 请注意adjList 中的元素是 Vertex 对象
unordered_map<Vertex*, unordered_set<Vertex*>> adjList;
public:
/* 构造方法 */
@ -52,7 +53,7 @@ public:
/* 添加顶点 */
void addVertex(Vertex* vet) {
if (adjList.count(vet)) return;
// 在邻接表中添加一个新链表(即 HashSet
// 在邻接表中添加一个新链表
adjList[vet] = unordered_set<Vertex*>();
}
@ -60,9 +61,9 @@ public:
void removeVertex(Vertex* vet) {
if (!adjList.count(vet))
throw invalid_argument("不存在顶点");
// 在邻接表中删除顶点 vet 对应的链表(即 HashSet
// 在邻接表中删除顶点 vet 对应的链表
adjList.erase(vet);
// 遍历其它顶点的链表(即 HashSet,删除所有包含 vet 的边
// 遍历其它顶点的链表,删除所有包含 vet 的边
for (auto& [key, set_] : adjList) {
set_.erase(vet);
}