如何检查两个节点是否与递归函数连接

How to check if two nodes are connected with recursive function

在一次采访中,我最近被问到一个类似的问题,如下所示:我必须构建一个递归函数来显示两个节点是否已连接。我怎样才能使下面的代码工作?有没有办法传递 a、b、c 'by reference',所以当它们被实例化时,这在我调用 check_connection 时有效。 Node 是一个可变对象,因此它应该像通过引用一样运行,但事实并非如此,因为存在错误:'NoneType is not iterable'。任何建议表示赞赏。

class Node():
    def __init__(self, neighbours):
        self.neighbours=neighbours

    def return_neighbours(self):
        return self.neighbours

def check_connection(first, second):
    connections=first.return_neighbours()
    for conection in connections:
        if second in conection:
            return True
        else:
            check_connection(conection,second)

a=None
b=None
c=None

a=Node(neighbours=[c])
b=Node(neighbours=[c])
c=Node(neighbours=[a,b])

check_connection(a,c)

问题是 None 不是可变对象。与其将 a、b、c 设置为 None,不如将它们设置为没有邻居的节点。这样它们就会被随后的声明所改变。正如您目前所拥有的那样,a 的邻居不是 c 而是 None,因为当时 c 只是一个指向 None 的变量,而不是对 Node 对象的引用。

这似乎有效:

class Node():
    def __init__(self):
        self.neighbours=None

def check_connection(first, second):
    if second in first.neighbours:
        print ("Connection found")
        exit()
    else:
        for conection in first.neighbours:
            check_connection(conection,second)

a=Node()
b=Node()
c=Node()

a.neighbours=[c]
b.neighbours=[c]
c.neighbours=[a,b]

check_connection(a,c)