Skip to content

Instantly share code, notes, and snippets.

@jakab922
Created October 15, 2016 10:50
Show Gist options
  • Save jakab922/01fafe1878a64bc16aae85aa54888531 to your computer and use it in GitHub Desktop.
Save jakab922/01fafe1878a64bc16aae85aa54888531 to your computer and use it in GitHub Desktop.
def has_directed_cycle(graph):
for node in graph.iterkeys():
frontline = [node]
was = set([node])
while frontline:
curr = frontline.pop()
if curr in was:
continue
was.add(curr)
for neighbor in graph[curr]:
if neighbor == node:
return True
else:
frontline.add(neighbor)
return False
if __name__ == "__main__":
node_count, edge_count = map(int, raw_input().strip().split())
graph = [set() for _ in xrange(node_count)]
for _ in xrange(edge_count):
fr, to = map(int, raw_input().strip().split())
graph[fr].add(to)
print has_directed_cycle(graph)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment