Advertisement
Guest User

Untitled

a guest
Dec 14th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. import itertools
  2.  
  3.  
  4. def strong_connect(vertex):
  5. global edges, indices, lowlinks, connected_components, index, stack
  6. indices[vertex] = index
  7. lowlinks[vertex] = index
  8. index += 1
  9. stack.append(vertex)
  10.  
  11. for v, w in (e for e in edges if e[0] == vertex):
  12. if indices[w] < 0:
  13. strong_connect(w)
  14. lowlinks[v] = min(lowlinks[v], lowlinks[w])
  15. elif w in stack:
  16. lowlinks[v] = min(lowlinks[v], indices[w])
  17.  
  18. if indices[vertex] == lowlinks[vertex]:
  19. connected_components.append([])
  20. while stack[-1] != vertex:
  21. connected_components[-1].append(stack.pop())
  22. connected_components[-1].append(stack.pop() + '$')
  23.  
  24.  
  25. # tarjan({1: [2], 2: [3, 4], 4: [5], 5: [2]})
  26. edges = [('1', '2'), ('2', '3'), ('2', '4'), ('4', '5'),
  27. ('5', '2')]
  28. vertices = list(v for v in itertools.chain(*edges))
  29. indices = dict((v, -1) for v in vertices)
  30. lowlinks = indices.copy()
  31. connected_components = []
  32.  
  33. index = 0
  34. stack = []
  35. for v in vertices:
  36. if indices[v] < 0:
  37. strong_connect(v)
  38.  
  39. print(connected_components)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement