Last active
May 8, 2021 18:48
-
-
Save wilderfield/189927130cc399cf3ca485808f2a3e82 to your computer and use it in GitHub Desktop.
Detect a Cycle in a Directed Graph Using DFS
This file contains 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
# Constants | |
UNVISITED = 0 | |
VISITED = 1 | |
EXPLORED = 2 | |
# Test Adjacency List Graph | |
# 0 -> 1 -> 2 -> 3 | |
graph = [[1], | |
[2], | |
[3], | |
[]] | |
def graphHasCycle(graph): | |
""" | |
:type graph List[List[int]] | |
:rtype: bool | |
""" | |
# Initialize State | |
state = [UNVISITED for i in range(len(graph))] | |
# Start DFS from each unvisited node | |
for node in range(len(graph)): | |
if state[node] == UNVISITED: | |
ret = subGraphHasCycle(graph,node,state) | |
if ret: | |
return True | |
return False | |
def subGraphHasCycle(graph, node, state): | |
if state[node] == VISITED: | |
return True | |
if state[node] == EXPLORED: | |
return False | |
state[node] = VISITED | |
for neighbor in graph[node]: | |
ret = subGraphHasCycle(graph, neighbor, state) | |
if ret: | |
return True | |
state[node] = EXPLORED | |
return False | |
print (graphHasCycle(graph)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment