Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

1 C We now wish to find the set of all nodes in the graph that belong to some cycle. Example Consider the example below:

1C
We now wish to find the set of all nodes in the graph that belong to some cycle.
Example
Consider the example below:
Nodes {0,2,3,4} lie on some cycle: example node 4 lies on many cycles one such cycle being 2-3-4. whereas the other nodes do not.
Note We do not treat undirected edges as cycles although in our data structure, when an undirected edge (i,j) is represented as two "directed" edges (i,j)
and (j,i), it gives the impression that they are in a cycle of length 2.
Complete the function find_all_nodes_in_cycle that given a graph returns a python set of nodes in a cycle.
Hint Perform a DFS traversal and for each non trivial back edge discovered, use the DFS tree to figure out the nodes that must be on the cycle corresponding
to that back edge.
In [60]: def find_all_nodes_in_cycle(g): # g is an UndirectedGraph class
set_of_nodes = set ()
# your code here
In [61]: #this is the example that we had for the problem.
g3= UndirectedGraph(8)
g3.add_edge (,1)
g3.add_edge (,2)
g3.add_edge (0,4)
g3.add_edge (2,3)
g3.add_edge (2,4)
g3.add_edge (3,4)
g3.add_edge (5,6)
g3.add_edge (5,7)
s= find_all_nodes_in_cycle (g3)
print (f' Your code returns set of nodes: {s}')
assert s=={0,2,3,4}, 'Fail: Set of nodes must be {0,2,3,4}.'
# Let's also add the edge 6,7
g3.add_edge (6,7)
s1= find_all_nodes_in_cycle (g3)
print(f' Your code returns set of nodes: {s1}')
assert s1=={0,2,3,4,5,6,7}, 'Fail: Set of nodes must be {0,2,3,4,5,6,7}.'
print('All tests passedd: 10 points!')
image text in transcribed

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

love of humour, often as a device to lighten the occasion;

Answered: 1 week ago

Question

orderliness, patience and seeing a task through;

Answered: 1 week ago

Question

well defined status and roles (class distinctions);

Answered: 1 week ago