76.0k views
0 votes
DFS and Cycles (20 pts) DFS classifies edges as tree edges, back edges, forward edges, and cross edges (see p. 609 in the CLRS textbook). (a) (5 pts) How can you modify the DFS pseudocode from the CLRS textbook to detect back-edges? Write down your modified pseudocode and explain why your modifications are sufficient. (b) (5 pts) How can you modify the DFS pseudocode from the CLRS textbook to determine whether a graph has a cycle? Write down the pseudocode and explain why your code returns a correct answer. Your procedure should return immediately as soon as it finds a cycle. (c) (5 pts) What is the runnning time of your cycle-detecting algorithm on directed graphs? Justify your answer. (d) (5 pts) What is the running time of your cycle-detecting algorithm on undirected graphs? Justify your answer.

1 Answer

4 votes

Final answer:

To modify the DFS pseudocode to detect back-edges, keep track of discovery and finish times. To determine if a graph has a cycle, check for back-edges. The running time of the cycle-detecting algorithm is O(V + E) for both directed and undirected graphs.

Step-by-step explanation:

(a) To modify the DFS pseudocode from the CLRS textbook to detect back-edges, we need to keep track of the discovery time and the finish time for each vertex. When we encounter an edge (u, v) during DFS, if v has already been discovered and v's finish time is smaller than u's discovery time, then it is a back-edge.

(b) To modify the DFS pseudocode to determine whether a graph has a cycle, we can use the same approach as detecting back-edges. If we encounter a back-edge during DFS, it means there is a cycle in the graph.

(c) The running time of the cycle-detecting algorithm on directed graphs is O(V + E), where V is the number of vertices and E is the number of edges in the graph. This is because we perform a depth-first search, which visits each vertex and edge once.

(d) The running time of the cycle-detecting algorithm on undirected graphs is also O(V + E). Although the runtime is the same, the approach is slightly different. In an undirected graph, we need to keep track of the parent of each vertex during DFS. If we encounter an edge (u, v) where v is already visited but v is not u's parent, it means there is a cycle.

User Arpan
by
7.9k points