minimario

Cycle Detection

Jun 19th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. **** CYCLE DETECTION IN DIRECTED GRAPH ****
  2.  
  3. void dfs (int v) {
  4. visited[v] = 1;
  5.  
  6. for every vertex that is reachable from v do
  7. if visited[vertex] = 0
  8. dfs (vertex)
  9. else if visited[vertex] = 1
  10. cycle = 1
  11.  
  12. visited[v] = 2
  13. }
  14.  
  15. ---------------------------------------------
  16.  
  17. **** RECOVER THE DFS PATH IN GRAPH ****
  18. dfs (int v) {
  19. visited[v] = 1;
  20.  
  21. for every vertex that is reachable from v :
  22. if visited[vertex] = 0 :
  23. parent[vertex] = v
  24. dfs (vertex)
  25. }
  26.  
  27. recover ( v ) {
  28. while parent[v] != -1 :
  29. print ( v )
  30. v = parent[v]
  31. }
  32. ---------------------------------------------
  33.  
  34. **** CYCLE DETECTION IN UNDIRECTED GRAPH ****
  35.  
  36. dfs ( v , parent = -1 ) {
  37. visited[v] = 1
  38.  
  39. for every vertex that is reachable from v :
  40. if vertex == parent : go to next vertex
  41. else if visited[vertex] == 0 :
  42. array_parent[vertex] = v
  43. dfs ( vertex, v )
  44. else if visited[vertex] == 1 :
  45. cycle = 1
  46. cycle_begin = vertex
  47. cycle_end = v
  48.  
  49. visited[v] = 2
  50. }
  51.  
  52. recover () {
  53. if cycle == 1 :
  54. answer = []
  55.  
  56. while (cycle_end != cycle_begin) :
  57. answer.append (cycle_end)
  58. cycle_end = array_parent[cycle_end]
  59.  
  60. print (answer)
  61. }
Advertisement
Add Comment
Please, Sign In to add comment