图的基础操作
跳转到“图的基础操作”以下处理无向简单图,边重复添加视为无变化,自环不允许。顶点值、顶点索引和对象地址是不同概念。保留十张原图,来源对照见Hello算法·图基础操作。
两组图演示同一串操作:初始顶点顺序[1,3,2,5,4],边为1—3、1—5、3—2、2—5、2—4、5—4,共六条;添加1—2后为七条,再删1—3、加孤立点6、删顶点3,最终有五条边。不能把这组初始图与上一节七边图混为一谈。
基于邻接矩阵的实现
跳转到“基于邻接矩阵的实现”矩阵代码的边参数是索引。例如顶点值1和2对应索引0和2。删除索引1即删除顶点值3,剩余索引会移动;外部保存的旧索引需要更新。顶点值可以重复,身份仍由索引决定。
已知合法索引后改边是O(1),需修改对称位置。删除顶点会删除一行,并移动其他行内元素,最坏O(n²);原稿“所有元素向左上移动”只是示意,不是二维vector真实内存布局。
新增顶点的O(n)应注明摊还意义:对n个行vector各追加一个元素,若多个行同时扩容,单次操作最坏可为O(n²)。从空图逐个添加n个顶点的总矩阵构建成本为O(n²)摊还,再处理m条边为O(m)。本例规模要求顶点数可由int表示。vector插入、扩容与删除规则
| 操作阶段 | 原图(可打开原尺寸) |
|---|---|
| 初始六条边 | ![]() |
| 添加1—2 | ![]() |
| 删除1—3 | ![]() |
| 添加孤立点6 | ![]() |
| 删除顶点3 | ![]() |
下面补齐标准头文件及打印函数,修复负索引删除和边记录长度检查。两个代码块分别独立编译为类定义;若合并到同一文件,只保留一份同名打印函数。调用样例由本轮测试驱动提供。
#include <vector>#include <iostream>#include <stdexcept>#include <algorithm>#include <unordered_map>using namespace std;
void printVector(const vector<int>& a) { for (int x : a) cout << x << " "; cout << "\n";}void printVectorMatrix(const vector<vector<int>>& a) { for (const auto& row : a) printVector(row);}
/* 基于邻接矩阵实现的无向图类 */class GraphAdjMat { vector<int> vertices; // 顶点列表,元素代表“顶点值”,索引代表“顶点索引” vector<vector<int>> adjMat; // 邻接矩阵,行列索引对应“顶点索引”
public: /* 构造方法 */ GraphAdjMat(const vector<int> &vertices, const vector<vector<int>> &edges) { // 添加顶点 for (int val : vertices) { addVertex(val); } // 添加边 // 请注意,edges 元素代表顶点索引,即对应 vertices 元素索引 for (const vector<int> &edge : edges) { if (edge.size() != 2) throw invalid_argument("edge needs two indices"); addEdge(edge[0], edge[1]); } }
/* 获取顶点数量 */ int size() const { return static_cast<int>(vertices.size()); }
const vector<int>& values() const { return vertices; } const vector<vector<int>>& matrix() const { return adjMat; }
/* 添加顶点 */ void addVertex(int val) { int n = size(); // 向顶点列表中添加新顶点的值 vertices.push_back(val); // 在邻接矩阵中添加一行 adjMat.emplace_back(vector<int>(n, 0)); // 在邻接矩阵中添加一列 for (vector<int> &row : adjMat) { row.push_back(0); } }
/* 删除顶点 */ void removeVertex(int index) { if (index < 0 || index >= size()) { throw out_of_range("顶点不存在"); } // 在顶点列表中移除索引 index 的顶点 vertices.erase(vertices.begin() + index); // 在邻接矩阵中删除索引 index 的行 adjMat.erase(adjMat.begin() + index); // 在邻接矩阵中删除索引 index 的列 for (vector<int> &row : adjMat) { row.erase(row.begin() + index); } }
/* 添加边 */ // 参数 i, j 对应 vertices 元素索引 void addEdge(int i, int j) { // 索引越界与相等处理 if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) { throw out_of_range("顶点不存在"); } // 在无向图中,邻接矩阵关于主对角线对称,即满足 (i, j) == (j, i) adjMat[i][j] = 1; adjMat[j][i] = 1; }
/* 删除边 */ // 参数 i, j 对应 vertices 元素索引 void removeEdge(int i, int j) { // 索引越界与相等处理 if (i < 0 || j < 0 || i >= size() || j >= size() || i == j) { throw out_of_range("顶点不存在"); } adjMat[i][j] = 0; adjMat[j][i] = 0; }
/* 打印邻接矩阵 */ void print() { cout << "顶点列表 = "; printVector(vertices); cout << "邻接矩阵 =" << endl; printVectorMatrix(adjMat); }};基于邻接表的实现
跳转到“基于邻接表的实现”此处是外层unordered_map加内层vector,不是“邻居也用哈希集合”。每条无向边存两份。外层哈希查询平均较快,不保证最坏常数;内层查重和删除仍需线性扫描邻居。无序关联容器规则
原稿只从边构造顶点,无法同时表达未出现在边中的孤立点。本轮增加显式顶点列表。Vertex*表示对象身份,不拥有对象:调用方必须保证对象在图使用期间存活、地址不变。不要把可能扩容的vector<Vertex>中元素的旧地址继续交给图。删除顶点只移除记录,不释放对象;同值的两个对象仍是不同顶点。
原代码允许重复插入边,但删除只删第一份,会在删除顶点后留下多余引用。本例改成幂等插边,并将邻接表设为私有,禁止绕过方法直接写入重复记录;空指针、自环和非双元素边记录均拒绝;对现有图调用addEdge/removeEdge时拒绝未知端点。构造器保留原设计,会把边中端点一并加入,显式顶点列表用于补入孤立点。下列教学实现没有为跨多个容器的分配失败提供事务式回滚,未宣称强异常保证。
| 操作阶段 | 原图(可打开原尺寸) |
|---|---|
| 初始六条边 | ![]() |
| 添加1—2 | ![]() |
| 删除1—3 | ![]() |
| 添加孤立点6 | ![]() |
| 删除顶点3 | ![]() |
#include <vector>#include <iostream>#include <stdexcept>#include <algorithm>#include <unordered_map>using namespace std;
void printVector(const vector<int>& a) { for (int x : a) cout << x << " "; cout << "\n";}struct Vertex { int val; };vector<int> vetsToVals(const vector<Vertex*>& a) { vector<int> values; for (const Vertex* v : a) values.push_back(v->val); return values;}
/* 基于邻接表实现的无向图类 */class GraphAdjList { // 邻接表,key:顶点,value:该顶点的所有邻接顶点 unordered_map<Vertex *, vector<Vertex *>> adjList;
public: const unordered_map<Vertex*, vector<Vertex*>>& neighbors() const { return adjList; }
/* 在 vector 中删除指定节点 */ void remove(vector<Vertex *> &vec, Vertex *vet) { for (size_t i = 0; i < vec.size(); i++) { if (vec[i] == vet) { vec.erase(vec.begin() + i); break; } } }
/* 构造方法 */ GraphAdjList(const vector<Vertex*>& vertices, const vector<vector<Vertex *>> &edges) { for (Vertex* v : vertices) addVertex(v); // 添加所有顶点和边 for (const vector<Vertex *> &edge : edges) { if (edge.size() != 2) throw invalid_argument("edge needs two vertices"); addVertex(edge[0]); addVertex(edge[1]); addEdge(edge[0], edge[1]); } }
/* 获取顶点数量 */ int size() { return static_cast<int>(adjList.size()); }
/* 添加边 */ void addEdge(Vertex *vet1, Vertex *vet2) { if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2) throw invalid_argument("不存在顶点"); // 简单图:重复插入同一条边不增加记录 const auto& row = adjList.at(vet1); if (find(row.begin(), row.end(), vet2) != row.end()) return; // 添加边 vet1 - vet2 adjList[vet1].push_back(vet2); adjList[vet2].push_back(vet1); }
/* 删除边 */ void removeEdge(Vertex *vet1, Vertex *vet2) { if (!adjList.count(vet1) || !adjList.count(vet2) || vet1 == vet2) throw invalid_argument("不存在顶点"); // 删除边 vet1 - vet2 remove(adjList[vet1], vet2); remove(adjList[vet2], vet1); }
/* 添加顶点 */ void addVertex(Vertex *vet) { if (!vet) throw invalid_argument("null vertex"); if (adjList.count(vet)) return; // 在邻接表中添加一个新链表 adjList[vet] = vector<Vertex *>(); }
/* 删除顶点 */ void removeVertex(Vertex *vet) { if (!adjList.count(vet)) throw invalid_argument("不存在顶点"); // 在邻接表中删除顶点 vet 对应的链表 adjList.erase(vet); // 遍历其他顶点的链表,删除所有包含 vet 的边 for (auto &adj : adjList) { remove(adj.second, vet); } }
/* 打印邻接表 */ void print() { cout << "邻接表 =" << endl; for (auto &adj : adjList) { const auto &key = adj.first; const auto &vec = adj.second; cout << key->val << ": "; printVector(vetsToVals(vec)); } }};效率对比
跳转到“效率对比”以下n为顶点数、m为边数、d(u)为顶点u的度;哈希项按通常平均情况,vector追加按摊还情况。表中邻接表指本页实际实现。
| 操作 | 邻接矩阵 | 外层哈希表+邻居vector |
|---|---|---|
| 判断u、v邻接 | O(1),已知索引 | O(d(u))扫描邻居,另有外层查询 |
| 添加边 | O(1) | O(d(u))查重+摊还追加,另有外层查询 |
| 删除边 | O(1) | O(d(u)+d(v))查找和移动 |
| 添加顶点 | O(n)摊还;单次最坏O(n²) | 平均摊还O(1),可能rehash |
| 删除顶点 | 最坏O(n²) | O(n+m)扫描全部邻居,加哈希查找/删除成本 |
| 存储 | O(n²) | O(n+m) |
若内层改为哈希集合,可以改变平均边查询/删除成本,但不能直接把那一列套到这里的vector代码。增加查重后,逐条构造邻接表也不再无条件是O(n+m):还要累计各次邻居扫描。没有一种表示在时间、空间、缓存局部性和所有操作上都最优。
本轮验证范围
跳转到“本轮验证范围”完整阅读250行原稿、现稿、两段代码、三张表和十张图。实际编译并运行文章中的两种C++实现,核对图示各阶段、对称性、重复边、孤立点、删除后索引及非法输入;另以独立边集作为小图比较基准。未进行性能基准、哈希碰撞压力或内存分配失败注入。









