viligen

cycles_in_graph_dfs

Aug 9th, 2022
582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | None | 0 0
  1. graph = {}
  2. visited = set()
  3. # cycles = set()
  4.  
  5. while True:
  6.     line = input().split('-')
  7.     if "End" == line[0]:
  8.         break
  9.     parent, child = line[0], line[1]
  10.     if parent not in graph:
  11.         graph[parent] = []
  12.     if child not in graph:
  13.         graph[child] = []
  14.     graph[parent].append(child)
  15.  
  16.  
  17. def dfs(node, graph, visited, cycles):
  18.     if node in cycles:
  19.         raise Exception
  20.     if node in visited:
  21.         return
  22.     visited.add(node)
  23.     cycles.add(node)
  24.  
  25.     for child in graph[node]:
  26.         dfs(child, graph, visited, cycles)
  27.     cycles.remove(node)
  28.  
  29.  
  30. try:
  31.     for node in graph:
  32.         dfs(node, graph, visited, set())
  33.     print('Acyclic: Yes')
  34. except Exception:
  35.     print('Acyclic: No')
Advertisement
Add Comment
Please, Sign In to add comment