Created
October 15, 2016 10:50
-
-
Save jakab922/01fafe1878a64bc16aae85aa54888531 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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