Skip to content

Instantly share code, notes, and snippets.

@abdellani
Last active October 8, 2019 15:03
Show Gist options
  • Save abdellani/318f2f35a6126589d4268fc7146f726f to your computer and use it in GitHub Desktop.
Save abdellani/318f2f35a6126589d4268fc7146f726f to your computer and use it in GitHub Desktop.
def check_cycle(graph,node,connected)
counter =0
return false if graph[node].nil?
graph[node].each do |element|
if connected.include?(element)
counter +=1
return true if counter ==2
else
connected<< element
return true if check_cycle(graph,element,connected)
end
end
false
end
def graph_cycle?(graph)
# write your code here
check_cycle(graph,0,[0])
end
puts graph_cycle?({
0=>[2],
1=>[4],
2=>[0, 5, 3],
3=>[5, 2],
4=>[5, 1],
5=>[4, 2, 3]
})
# => true
puts graph_cycle?({
0=>[2],
1=>[2],
2=>[0, 1, 3, 4, 5],
3=>[2],
4=>[2]
})
# => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment