找到使用所有给定边python的路径

时间:2013-12-17 14:54:16

标签: python topological-sort

我有一个边缘列表。我需要解码从源节点到汇聚节点的路径。我的路径中可能有循环,但我应该只使用每个边缘一次。在我的列表中,我可能也有多次相同的边缘,这意味着在我的路径中我应该多次传递它。

让我们说我的边列表如下:

[(1, 16), (9, 3), (8, 9), (15, 8), (5, 1), (8, 15), (3, 5)]

所以我的路径是:

8->15->8->9->3->5->1->16 equivalent to [8,15,8,9,3,5,1,16]

我知道汇聚节点和源节点。 (在上面的示例中我知道8是源,16是接收)这里是另一个使用相同边缘的多个样本:

[(1,2),(2,1),(2,3),(1,2)]

路径是:

1->2->1->2->3 equivalent to [1,2,1,2,3]

基本上它是拓扑排序的类型,但是我们在拓扑排序中没有循环。我有以下代码,但它不使用循环中的节点!

def find_all_paths(graph, start, end):
    path  = []
    paths = []
    queue = [(start, end, path)]
    while queue:
        start, end, path = queue.pop()
        print 'PATH', path

        path = path + [start]
        if start == end:
            paths.append(path)
        for node in set(graph[start]).difference(path):
            queue.append((node, end, path))
return paths

1 个答案:

答案 0 :(得分:0)

简单地说,您可能需要在边缘上进行多次传递,以使用所有边缘组合路径。

所包含的代码按以下假设运作:

  • 存在解决方案。即所有顶点都属于底层图形的单个连通组件,并且
  • in_degree = out_degree,除了2个顶点之外的全部或全部。在后一种情况下,其中一个顶点为in_degree - out_degree = 1,另一个顶点为in_degree - out_degree = -1。

此外,即使有这些条件,对于利用所有边缘找到从源到汇的路径的问题也不一定是唯一的解决方案。此代码只找到一个解决方案而不是所有解决方案。 (存在多个解决方案的示例是'daisy'[(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5),(5,1)],其中起点和终点相同。)

我们的想法是为边缘的起始节点索引的路径创建所有边的字典,然后在将字体添加到路径时从字典中删除边。我们不是试图在第一遍中获取路径中的所有边缘,而是多次遍历字典直到使用所有边缘。第一遍创建从源到接收器的路径。后续传递添加循环。

警告:几乎没有一致性检查或验证。如果开始不是边缘的有效源,那么返回的'path'将被断开!

"""
This is a basic implementatin of Hierholzer's algorithm as applied to the case of a 
directed graph with perhaps multiple identical edges.
"""

import collections

def node_dict(edge_list):
    s_dict = collections.defaultdict(list)
    for edge in edge_list:
        s_dict[edge[0]].append(edge)
    return s_dict

def get_a_path(n_dict,start):
    """
    INPUT:  A dictionary whose keys are nodes 'a' and whose values are lists of 
    allowed directed edges (a,b) from 'a' to 'b', along with a start WHICH IS 
    ASSUMED TO BE IN THE DICTIONARY.

    OUTPUT:  An ordered list of initial nodes and an ordered list of edges 
    representing a path starting at start and ending when there are no other 
    allowed edges that can be traversed from the final node in the last edge.

    NOTE:  This function modifies the dictionary n_dict!
    """

    cur_edge = n_dict[start][0]
    n_dict[start].remove(cur_edge)

    trail = [cur_edge[0]]
    path = [cur_edge]
    cur_node = cur_edge[1]

    while len(n_dict[cur_node]) > 0:
        cur_edge = n_dict[cur_node][0]
        n_dict[cur_node].remove(cur_edge)
        trail.append(cur_edge[0])
        path.append(cur_edge)
        cur_node = cur_edge[1]

    return trail, path


def find_a_path_with_all_edges(edge_list,start):
    """
    INPUT:  A list of edges given by ordered pairs (a,b) and a starting node.

    OUTPUT:  A list of nodes and an associated list of edges representing a path 
    where each edge is represented once and if the input had a valid Eulerian 
    trail starting from start, then the lists give a valid path through all of 
    the edges.

    EXAMPLES:

        In [2]: find_a_path_with_all_edges([(1,2),(2,1),(2,3),(1,2)],1)
        Out[2]: ([1, 2, 1, 2, 3], [(1, 2), (2, 1), (1, 2), (2, 3)])

        In [3]: find_a_path_with_all_edges([(1, 16), (9, 3), (8, 9), (15, 8), (5, 1), (8, 15), (3, 5)],8)
        Out[3]: 
        ([8, 15, 8, 9, 3, 5, 1, 16],
         [(8, 15), (15, 8), (8, 9), (9, 3), (3, 5), (5, 1), (1, 16)])
    """

    s_dict = node_dict(edge_list)
    trail, path_check = get_a_path(s_dict,start)

    #Now add in edges that were missed in the first pass...
    while max([len(s_dict[x]) for x in s_dict]) > 0:
        #Note:  there may be a node in a loop we don't have on trail yet
        add_nodes = [x for x in trail if len(s_dict[x])>0]
        if len(add_nodes) > 0:
            skey = add_nodes[0]
        else:
            print "INVALID EDGE LIST!!!"
            break

        temp,ptemp = get_a_path(s_dict,skey)
        i = trail.index(skey)
        if i == 0:
            trail = temp + trail
            path_check = ptemp + path_check
        else:
            trail = trail[:i] + temp + trail[i:]
            path_check = path_check[:i] + ptemp + path_check[i:]

    #Add the final node to trail.
    trail.append(path_check[-1][1])
    return trail, path_check