mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
Update graph codes
This commit is contained in:
@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user