【问题标题】:How to determine if two nodes are part of a same tree/graph?如何确定两个节点是否属于同一棵树/图?
【发布时间】:2017-10-06 03:43:16
【问题描述】:

我在一次采访中被问到这个问题,以确定两个人是否在 facebook 上直接或间接联系。

假设 a 有几个朋友 b,c,d,e 和 c 有几个朋友 b,d,f,g 和 f 有朋友 x,y,z。那么 a 和 z 是间接朋友。

有没有很好的算法来找出它们是如何连接的?

This 帖子有类似的问题,但他的标准太多,所以我认为必须有更好的方法来做到这一点。谁能给点建议?

【问题讨论】:

    标签: algorithm graph tree binary-search-tree nodes


    【解决方案1】:

    运行Breadth First Search 以获取到达该特定朋友的最少跃点(如果可以到达)。通过对到目前为止访问的节点进行一些记录,您将能够让好友遍历以到达正在搜索的好友。

    此算法在线性时间O(V + E) 中运行。

    伪代码:

    广度优先搜索(图、根、目标):

    create empty set Checked
    create empty queue Queue      
    
    add Root to Checked
    Queue.enqueue(Root)                      
    
    while Queue is not empty {
        Current = Queue.dequeue()
        if Current.has(Goal) {
            return Current
        }
        for each Node that is adjacent to Current {
            if Node is not in Checked {
                Checked.add(Node)
                Queue.enqueue(Node)
            }
        }
    }
    

    如果在找到正在搜索的朋友之前需要访问的朋友大于1,则可以说他们是间接连接的。

    这也可以用来检查它们是否连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2021-12-20
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多