获取两个节点之间所有可能的简单路径(图论)

时间:2018-02-05 17:04:00

标签: python graph np

在图论的背景下,我试图获得两个节点之间所有可能的简单路径。

我使用存储在pandas数据帧中的邻接矩阵记录网络,网络[x] [y]存储从x到y的箭头值。

要获取两个节点之间的路径,我所做的是:

我得到了所有节点的所有可能的排列(使用它。精子 - 路径很简单,没有重复)。 然后我使用ad hoc函数:adjacent(它给我一个节点的邻居),检查所有可能的路径中哪一个是真的。

这需要太长时间,而且效率不高。你知道我如何改进代码吗?可能带有递归函数??

出于非相关原因,我不想使用Networkx

def get_simple_paths(self, node, node_objective):

    # Gives you all simple path between two nodes

    #We get all possibilities and then we will filter it
    nodes = self.nodes #The list of all nodes
    possible_paths = [] #Store all possible paths
    simple_paths = [] #Store the truly paths
    l = 2        
    while l <= len(nodes):
        for x in it.permutations(nodes, l): #They are neighbourgs
            if x[0] == node and x[-1] == node_objective:
                possible_paths.append(x)
        l += 1

    # Now check which of those paths exists
    for x_pos, x in enumerate(possible_paths):
        for i_pos, i in enumerate(x): 
#We use it to check among all the path, 
#if two of the nodes are not neighbours, the loop brokes 
            if i in self.adjacencies(x[i_pos+1]):
                if i_pos+2 == len(x):
                    simple_paths.append(x)
                    break
                else:
                    continue
            else:
                break
    #Return simple paths    
    return(simple_paths)

0 个答案:

没有答案