2 years ago

#39323

test-img

JanieM

Longest series that can be built from a given graph edges

I'm trying to build a program that finds the longest series that can be built from a given edges represented by list of tuples with pair of values, i.e:

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

Edges can be rotated when connected!

The program should return length of 5, because

2-1   1-2   2-17   17-2   2-3

I tried DFS approach but without any success.

from collections import deque, defaultdict

def DFS(G, v, seen=None, path=None):
   if seen is None: seen = []
   if path is None: path = [v]

   seen.append(v)

   paths = []
   for t in G[v]:
       if t not in seen:
           t_path = path + [t]
           paths.append(tuple(t_path))
           paths.extend(DFS(G, t, seen[:], t_path))
   return paths

data = [(1,2), (1,2), (2,3), (2,17), (2,17)]
G = defaultdict(list)
for (s,t) in data:
    G[s].append(t)
    G[t].append(s)

result = [p for ps in [DFS(G, n) for n in set(G)] for p in ps]

Is there any simple way of adjusting my script to achieve desired output?

python

algorithm

depth-first-search

breadth-first-search

0 Answers

Your Answer

Accepted video resources