krahets / hello-algo

《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 代码。简体版和繁体版同步更新,English version ongoing
https://www.hello-algo.com
Other
95.04k stars 12.07k forks source link

Update graph_adjacency_matrix.py #1464

Closed Fuuuuuji closed 1 month ago

Fuuuuuji commented 1 month ago

理解K神这个实现主要是为了演示邻接矩阵的基本原理,但在实际使用中可能会遇到一些限制:在实际应用中,通常使用顶点的值而不是索引来操作图。所以,为了更“公平”地与邻接表方法的对比,进行了改进:

  1. 引入 vertex_map:使用字典 vertex_map 来存储顶点值到索引的映射。
  2. 基于值的操作:add_vertex, remove_vertex, add_edge, 和 remove_edge 方法现在都使用顶点值而不是索引。这使得图的操作更加直观和用户友好。
  3. 动态索引管理:在 remove_vertex 方法中,更新了剩余顶点的索引映射。这确保了在删除顶点后,其他顶点的索引仍然保持正确。

If this pull request (PR) pertains to Chinese-to-English translation, please confirm that you have read the contribution guidelines and complete the checklist below:

If this pull request (PR) is associated with coding or code transpilation, please attach the relevant console outputs to the PR and complete the following checklist:

krahets commented 1 month ago

在实际应用中,通常使用顶点的值而不是索引来操作图

这样无法处理有节点值重复的情况,我倾向于保留当前实现