作者:妩媚舞乙 | 来源:互联网 | 2023-02-01 21:31
这个问题的研究对象是小规模的有向图。我们用字典来保存图中两点的拓扑关系,每个字典的键代表相应的点,键值是该点向外的直接连接对象,而且边是单向的。算法的目的是找到一条从起点到终点的任
这个问题的研究对象是小规模的有向图。
我们用字典来保存图中两点的拓扑关系,每个字典的键代表相应的点,键值是该点向外的直接连接对象,而且边是单向的。
算法的目的是找到一条从起点到终点的任一路径,不一定是最长或最短。找到之后输出经过的点,没有找到则返回空列表。
算法的具体实现是通过经典的深度优先递归法:1、遍历起点的直接连接点,将其作为新的起点,同时将这个点加入已经考察过的点集;2、再遍历新起点的直接连接点;3、加入要考察的点都已经出现在考察过的点集,返回空集,如果找到了终点,则返回以该点为第一个元素、终点为第二个元素的列表;4、要传递的参数,包括网络,终点和起点,考察过的点集;5、返回非空列表时意味着找到了路径,才会保留。
下面是具体的代码实现,用的是python2.7,还有一个简单的例子。
以下是文本格式的代码:
#to find a path between to nodes by recursion
network = {'A':[['D', 'C'], ['X', 'Y']], 'B':[['A','C', 'D'],['Y','Z']],
'C':[['D'],['X']], 'D':[['B', 'E'],[]], 'E':[['C'],[]], 'F':[['A'], ['Y']]}
searched = []
def find_path_to_friend(network, user_A, user_B, searched):
if user_A not in searched:
searched.append(user_A)
#add the starting point to the searched list
if user_A not in network or user_B not in network:
#if the two user is not in the network, return none
return None
if user_B in network[user_A][0]:
#if B is in A's reach, just return the two
return [user_A, user_B]
else:
for e in network[user_A][0]:
if e in searched:
#if node 'e' is searched before, skip it
continue
searched.append(e)
#add 'e' to the searched list
#print searched
sequence = find_path_to_friend(network, e, user_B, searched)
if sequence:
return [user_A] + sequence
#if the outcome of the last recursion is not
return []
#empty, it indicates that we have got the destination
#if not, this path would not be record
#
print find_path_to_friend(network, 'D', 'F', searched)