How to implement detection of undirected and directed loops in Java
Undirected rings An undirected graph with rings is shown below, where there are two rings, 0-2-1-0 and 2-3-4-2, respectively.
To detect rings in an undirected graph, you can use depth-first search. Suppose we start from vertex 0, then walk to the adjacent vertex 2, then walk to the vertex 1 adjacent to vertex 2. Since vertex 0 and vertex 1 are adjacent and vertex 0 is labeled, it means we have spared a loop, so there is a loop in the undirected graph.