Advertisement
GalinaKG

02. Cycles in Graph

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