krahets / hello-algo

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

fix(graph): enhance the judgment of boundary conditions for removeEdge functions #1412

Open ztkuaikuai opened 1 week ago

ztkuaikuai commented 1 week ago

9.2.2 基于邻接表的实现中 JS 和 TS 代码片段 removeEdge 函数如果传入的两个顶点不为邻接点,那么在对应邻接表 adjList 中查找不到对应的顶点,返回 -1,继续执行则会删除顶点的邻接顶点表最后一项,即 splice(-1, 1)

通过添加边界条件判断两顶点是否为邻接点修复此问题。

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:

相关代码控制台输出:

初始化后,图为
邻接表 =
1: 3,5
3: 1,2
2: 3,5,4
5: 2,1,4
4: 2,5

添加边 1-2 后,图为
邻接表 =
1: 3,5,2
3: 1,2
2: 3,5,4,1
5: 2,1,4
4: 2,5

删除边 1-3 后,图为
邻接表 =
1: 5,2
3: 2
2: 3,5,4,1
5: 2,1,4
4: 2,5

添加顶点 6 后,图为
邻接表 =
1: 5,2
3: 2
2: 3,5,4,1
5: 2,1,4
4: 2,5
6:

删除顶点 3 后,图为
邻接表 =
1: 5,2
2: 5,4,1
5: 2,1,4
4: 2,5
6: