假设您有一个字典,其中包含图形的顶点值,如下所示:
graph = {'A':['B', 'C'], 'B': ['C', 'D'], 'C':['D', 'F'], D:[], F:[E], E: ['F']}
*为简单起见,图表不是双向的。这意味着如果A连接到B,这并不一定意味着B连接到A.
问题:为所有顶点获得高达 N 度的连接度。
我知道这是一个非常复杂的问题。那么有什么方法,除了多个for
循环来看它吗?也许有些论文你也可以参考我?必须有更好的方法来查看它,因为使用for
循环可能达到O(n ^ n)复杂度(如果我没有弄错的话)。
我的代码计算最多 2 连接度是这样的:
def getDegreesOfConnectivity(graph):
'''
Based on a dictionary with the graphs vertexes creates a list of dictionaries for degrees of connectivity.
Args:
:param graph (dictionary): A dictionary whose keys are the vertexes and the values are the vertexes to which they go
**direct** interactions.
Returns:
list of dictionaries: A list containing dictionaries. Each dictionary has **3** keys.
vertex: Starting node in which we start looking at the **path**
first_degree_of_connectivity: All the vertexes that are directly connected to **initial** vertex
second_degree_of_connectivity: Multiple **lists** of vertexes connected to each vertex in the **first_degree_of_connectivity**.
'''
sys.stdout.write("Calculating degrees of connectivity...\n")
li = []
# For easier understanding, assume vertex1 refers to vertex in the 1st level of connectivity.
# vertex2, to vertex with 2 levels of connectivity, etc...
for vertex1 in graph:
dic = {}
dic['vertex'] = vertex1
dic['first_degree_of_connectivity'] = graph[vertex1]
dic['second_degree_of_connectivity'] = []
# This was the easy part. Now to get the 2nd degree of connectivity...
#dic['second_degree_of_connectivity']
for vertex2 in graph[vertex1]:
# look in to the first degree of connectivity vertexes and compare them with our data. That means
# go through the graph data again. for every vertex...
if vertex2 in graph:
dic['second_degree_of_connectivity'].append(graph[vertex2])
li.append(dic)
return li
答案 0 :(得分:0)
def findNode(graph,head,target):
if head == target: return 0
if not graph[head]: return float('inf') # hackery ... basically means no path
return 1 + min(findNode(graph,child,target) for child in graph[head])
可能是我将如何递归地解决这个问题(警告它会破坏非常深的图的递归深度)
答案 1 :(得分:0)
PIP存储库中的模块vertex connectivity上存在一个计算python-igraph的python实现。
请参阅文档,网址为
请注意,它并不以字典作为输入,而是提供了几种实例化图形的方法。