Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle detection in a graph

We are given a graph with the following facts:

edge(a,b)
edge(a,c)
edge(b,a)
edge(c,d)
edge(d,d)
edge(d,e)
edge(e,f)
edge(f,g)
edge(g,e)

And we are asked to define a rule, cycle(X), that determines if there is a cycle starting from the node X.

I am really lost on how to do this, I tried attempting to traverse the nodes and checking if the next one would be the starting one again but I cannot seem to get it to work

like image 647
Steve Avatar asked Jul 17 '11 00:07

Steve


People also ask

How does BFS detect cycle in a graph?

We do a BFS traversal of the given graph. For every visited vertex 'v', if there is an adjacent 'u' such that u is already visited and u is not a parent of v, then there is a cycle in the graph. If we don't find such an adjacent for any vertex, we say that there is no cycle.

How do you define a cycle on a graph?

A Cycle Graph or Circular Graph is a graph that consists of a single cycle. In a Cycle Graph number of vertices is equal to number of edges. A Cycle Graph is 2-edge colorable or 2-vertex colorable, if and only if it has an even number of vertices.

How can you detect a cycle in a graph using adjacency matrix?

Start from an edge (i,j) Select the set O of edges which are outgoing from j , i.e., all the 1s in the j -th row of A. Navigate O in a DFS fashion. If one of the paths generated from this navigation leads to the node i , then a cycle is detected.


1 Answers

Archie's idea is a good starting point, but it will create an infinite loop if it finds another cycle while searching for the path.

I also haven't used prolog for years, but you will need something like path(X,Y,Visited), where you keep track of the visited nodes, preventing the endless loops.

like image 92
Karoly Horvath Avatar answered Sep 19 '22 18:09

Karoly Horvath