Skip to content

Instantly share code, notes, and snippets.

@langford
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save langford/6dd2de2683d1684650e5 to your computer and use it in GitHub Desktop.
Save langford/6dd2de2683d1684650e5 to your computer and use it in GitHub Desktop.
linear cycle detection in a directed graph (pseudocode)
graph data struture:{
list-of-all-nodes
head
}
node data structure:{
data
childrenList
hasBeenSeen
}
allocateNode(graph,childrenListRef){
node = malloc()
graph.list-of-all-nodes = cons(node,graph.list-of-all-nodes)
childrenListRef->add(node)
}
deleteNode(graph,node){
//precondition, already removed it from the childrenList of it's parent node
graph.list-of-all-nodes = remove(graph.list-of-all-nodes,node)
free(node)
}
traverseCheck(node)->bool{
for(child in node.childrenList){
if(child.hasBeenSeen){
//OH NO, CYCLE
return TRUE //aka, it is a cycle
}else{
child.hasBeenSeen = TRUE
}
}
}
clearMarkings(graph){
for(node in graph){
node.hasBeenSeen = FALSE
}
}
isCyclical(graph) ->Bool{
clearMarkings(graph)
for (node in graph.list-of-all-nodes) { //O(N) where N is node count
//this is Kyle's suggestion
if(traverseCheck(node)){
return TRUE
}
//we also have to do the check on everything else in the list that isn't already marked...it could be a disconnected region
if(!node.hasBeenSeen){
for(child in node.childrenList){
if(traverseCheck(child)){
return TRUE
}
}
}
}
return FALSE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment