列出所有TSP路线组合(5个顶点)

时间:2018-12-09 14:09:57

标签: python sorting graph combinations traveling-salesman

我想列出所有TSP路线组合。

有5个顶点,因此有10条边: enter image description here

所有边缘如下:

edges = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E')]

注意:('A', 'B')('B', 'A')相同,其他边缘也一样。 我想列出所有从A开始并互相访问并在A处结束的路线组合。

这是我到目前为止得到的:

edges = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E')]
x = list(itertools.permutations(['A','B','C','D','E', 'A'], 6))

b = 1
for i in x:
    if i[-1] == 'A' and i[0] == 'A':
        print(i, b)
        b += 1

但是,我不想重复路线。我该如何解决呢? 例如。 A-> B-> C-> A与A-> C-> B-> A相同,因此不应计数/列出两次。

1 个答案:

答案 0 :(得分:0)

您可以将递归与生成器一起使用:

edges = [('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E')]
def all_paths(graph, start, end=None, _flag = None, _pool = [], _seen= []):
   if start == end:
      yield _pool
   else:
      for a, b in graph:
        if a == start and a not in _seen:
          yield from all_paths(graph, b, end=_flag, _flag=_flag, _pool = _pool+[b], _seen =_seen+[a])


results = list(all_paths(edges+[(b, a) for a, b in edges], 'A', _flag = 'A'))
filtered = [a for i, a in enumerate(results) if not any(len(c) == len(a) and all(h in c for h in a) for c in results[:i])]

输出:

[['B', 'C', 'D', 'E', 'A'], ['B', 'C', 'D', 'A'], ['B', 'C', 'E', 'A'], ['B', 'C', 'A'], ['B', 'D', 'E', 'A'], ['B', 'D', 'A'], ['B', 'E', 'A'], ['B', 'A'], ['C', 'D', 'E', 'A'], ['C', 'D', 'A'], ['C', 'E', 'A'], ['C', 'A'], ['D', 'E', 'A'], ['D', 'A'], ['E', 'A']]