0

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?

JanieM
  • 17
  • 4
  • 3
    Longest path is np-hard. DFS is not gonna work out. – Christian Sloper Jan 11 '22 at 20:45
  • Is your input an undirected graph? as in with (1,2) you can only go from 1 to 2 or you can go from either '1 to 2' or '2 to 1'. If it is an undirected graph, can you have multiple edges between two vertices? (1,2), (1,2) would mean I can go between 1<>2 twice in my longest path calculation? If your input size is small enough you can use DFS to get a determistic answer in exponential time, otherwise you will have to use some heuristic approach to get approx value for longest path length. – Jay Jan 12 '22 at 08:57
  • Sorry, I've added note: "Edges can be rotated when connected!" – JanieM Jan 12 '22 at 09:20
  • Can there be multiple edges between two vertexes? e.g. for `[(1,2),(1,2),(1,2),(1,2)]` the answer would be 4(because we can go 1 > 2 > 1 > 2 > 1)? The reason your DFS is incorrect is because `t not in seen` check, because of it, you would only be visiting a vertex once at most in all your paths. For `G` try using a `defaultdict(defaultdict(int))` there which keeps count of repeated edges across vertexes instead of a `defaultdict(list)`. – Jay Jan 12 '22 at 14:42
  • For [(1,2),(1,2),(1,2),(1,2)] the answer would be 4, that's correct but because we can go 2-1 > 1-2 > 2-1 > 1-2. – JanieM Jan 12 '22 at 15:16

0 Answers0