Sunday, March 11, 2012

Cycle in a graph.


Check if the graph has atleast one cycle.


Approach:
Example graph:
A B C D -> number of nodes.
A B -> node A is connected to B
B C -> node B is connected to C.
C A -> node C is connected to A.
D A C -> node D is connected A and C.
Indegree of nodes are:
A:2
B:1
C:2
D:0


Now pick the node with indegree 0, and remove from the graph (ie remove all the outgoing edges from D) and update the indegrees.
So now we have the indegrees as:
A:1
B:1
C:1


Now there is no node with indegree 0, that means the graph has cycle.
Note: With this approach we dont know what nodes are part of the cycle.


Example 1:
A B C D -> number of nodes.
A B -> node A is connected to B
B C D -> node B is connected to C and D.
C A D -> node C is connected to A and D
D -> node D is not connected to any node in the graph.
printing adjacency list: 
A B 
B C D 
C A D 

printing indegree of nodes: 
D:2
A:1
B:1
C:1
Does Graph has cycle ? true


Example 2:
A B C D
A B C D
B C D
C D
D
printing adjacency list: 
A B C D 
B C D 
C D 

printing indegree of nodes: 
D:3
A:0
B:1
C:2
Does Graph has cycle ? false

No comments:

Post a Comment