Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- **** CYCLE DETECTION IN DIRECTED GRAPH ****
- void dfs (int v) {
- visited[v] = 1;
- for every vertex that is reachable from v do
- if visited[vertex] = 0
- dfs (vertex)
- else if visited[vertex] = 1
- cycle = 1
- visited[v] = 2
- }
- ---------------------------------------------
- **** RECOVER THE DFS PATH IN GRAPH ****
- dfs (int v) {
- visited[v] = 1;
- for every vertex that is reachable from v :
- if visited[vertex] = 0 :
- parent[vertex] = v
- dfs (vertex)
- }
- recover ( v ) {
- while parent[v] != -1 :
- print ( v )
- v = parent[v]
- }
- ---------------------------------------------
- **** CYCLE DETECTION IN UNDIRECTED GRAPH ****
- dfs ( v , parent = -1 ) {
- visited[v] = 1
- for every vertex that is reachable from v :
- if vertex == parent : go to next vertex
- else if visited[vertex] == 0 :
- array_parent[vertex] = v
- dfs ( vertex, v )
- else if visited[vertex] == 1 :
- cycle = 1
- cycle_begin = vertex
- cycle_end = v
- visited[v] = 2
- }
- recover () {
- if cycle == 1 :
- answer = []
- while (cycle_end != cycle_begin) :
- answer.append (cycle_end)
- cycle_end = array_parent[cycle_end]
- print (answer)
- }
Advertisement
Add Comment
Please, Sign In to add comment