查看: 1362| 回复: 4
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] 图直径算法求教

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x



关于这个经典的图直径算法,我有一个反例不知道怎么理解。


To find the diameter of a graph using BFS, follow these steps:
  • Choose any node, source, in the graph.
  • Run BFS from source to compute the shortest path to every other node in the graph.
  • Find the node, farthest_node, with the maximum shortest path distance from source.
  • Run BFS again from farthest_node to compute the shortest path to every other node.
  • The maximum shortest path distance found during the second BFS iteration represents the diameter of the graph.

The BFS algorithm guarantees that we visit all nodes in breadth-first order, ensuring that we find the shortest path between any two nodes efficiently.


reference: https://saturncloud.io/blog/algo...or-data-scientists/


反例是这样的:


2 - 4 - 1 - 5
         \     /
           3


如果在第一步choose any source的时候选择了 1,那第3步的farthest_node就可以是2或者3。这时候,如果我们选择3作为起点开始跑第二个BFS,就会得到错误的结论——该图的直径为2。求教我在哪一步理解错了,还是说farthest_node有tie的时候,有特殊操作?





评分

参与人数 1大米 +2 收起 理由
14417335 + 2 给你点个赞!

查看全部评分


上一篇:[LC周赛赛后发布会] Weekly Contest 365
下一篇:leetocde 505 请帮忙诊断我的DFS解法
推荐
mc2 2023-10-2 06:43:38 | 只看该作者
全局:
对于有环图,链接的方法很明显是错的。
我觉得应该用All pairs shortest path的算法。

评分

参与人数 1大米 +1 收起 理由
14417335 + 1 给你点个赞!

查看全部评分

回复

使用道具 举报

全局:
3为起点的BFS,最远的不是5吗?
回复

使用道具 举报

🔗
SoWhat0309 2023-10-2 13:17:26 | 只看该作者
全局:
链接的解法应该只适用于树图(树任意两点间就一条路,可以用这个性质反证)。

评分

参与人数 1大米 +1 收起 理由
14417335 + 1 给你点个赞!

查看全部评分

回复

使用道具 举报

全局:

评分

参与人数 1大米 +1 收起 理由
14417335 + 1 给你点个赞!

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表