6

I am having some trouble writing an algorithm that returns all the paths forming simple cycles on an undirected graph.

I am considering at first all cycles starting from a vertex A, which would be, for the graph below

A,B,E,G,F
A,B,E,D,F
A,B,C,D,F
A,B,C,D,E,G,F

Additional cycles would be

B,C,D,E
F,D,E,G

but these could be found, for example, by calling the same algorithm again but starting from B and from D, respectively.

The graph is shown below -

enter image description here

My current approach is to build all the possible paths from A by visiting all the neighbors of A, and then the neighbors of the neightbors and so on, while following these rules:

  • each time that more than one neighbor exist, a fork is found and a new path from A is created and explored.

  • if any of the created paths visits the original vertex, that path is a cycle.

  • if any of the created paths visits the same vertex twice (different from A) the path is discarded.

  • continue until all possible paths have been explored.

I am currently having problems trying to avoid the same cycle being found more than once, and I am trying to solve this by looking if the new neighbor is already part of another existing path so that the two paths combined (if independent) build up a cycle.

My question is: Am I following the correct/better/simpler logic to solve this problem.?

I would appreciate your comments

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Jose Ospina
  • 2,097
  • 3
  • 26
  • 40
  • See http://stackoverflow.com/questions/5068086/finding-all-cycles-in-an-undirected-graph. Simple-looking graphs can easily have the worst case exponential number of cycles. Why do you need to do this? – Gene Jan 04 '13 at 01:54
  • The links within the link you give are for directed graphs. But now I am starting to think that one solution, is to use those algorithms replacing each edge by two directed edges and ignoring all cycles made by only two vertices. I want the cycles for a layout algorithm, I know its heavy load but I am working with few < 50 nodes. – Jose Ospina Jan 04 '13 at 12:08
  • I have tried the algorithm for directed graphs mentioned by @eminsenay in [link](http://stackoverflow.com/questions/546655/finding-all-cycles-in-graph), which can be downloaded from [link] http://normalisiert.de/code/java/elementaryCycles.zip). I changed each edge with two directed edges, and it works almost well, it gives me the same cycle twice, one for each direction. Do I have to compare all the returned cycles to see if any of them is equivalent to another?, they could start from different nodes and be equivalent cycles too. – Jose Ospina Jan 04 '13 at 12:42
  • Maybe there is a simplified version of the algorithm in [link](http://dutta.csc.ncsu.edu/csc791_spring07/wrap/circuits_johnson.pdf) (which is implemented in Java in the elemenetaryCycles.zip file above) for undirected graphs such that cycles of length 2 are not considered and such that the direction of a cycle is ignored... It should be faster since less cycles exists... – Jose Ospina Jan 04 '13 at 12:46

2 Answers2

4

Based on the answer of @eminsenay to other question, I used the elementaryCycles library developed by Frank Meyer, from web_at_normalisiert_dot_de which implements the algorithms of Johnson.

However, since this library is for directed graphs, I added some routines to:

  • build the adjacency matrix from a JGraphT undirected graph (needed by Meyer's lib)
  • filter the results to avoid cycles of length 2
  • delete repeated cycles, since Meyer's lib is for directed graphs, and each undirected cycle is two directed cycles (one on each direction).

The code is

package test;

import java.util.*;

import org.jgraph.graph.DefaultEdge;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.SimpleGraph;


public class GraphHandling<V> {

private UndirectedGraph<V,DefaultEdge>     graph;
private List<V>                         vertexList;
private boolean                         adjMatrix[][];

public GraphHandling() {
    this.graph             = new SimpleGraph<V, DefaultEdge>(DefaultEdge.class);
    this.vertexList     = new ArrayList<V>();
}

public void addVertex(V vertex) {
    this.graph.addVertex(vertex);
    this.vertexList.add(vertex);
}

public void addEdge(V vertex1, V vertex2) {
    this.graph.addEdge(vertex1, vertex2);
}

public UndirectedGraph<V, DefaultEdge> getGraph() {
    return graph;
}

public List<List<V>>     getAllCycles() {
    this.buildAdjancyMatrix();

    @SuppressWarnings("unchecked")
    V[] vertexArray                 = (V[]) this.vertexList.toArray();
    ElementaryCyclesSearch     ecs     = new ElementaryCyclesSearch(this.adjMatrix, vertexArray);

    @SuppressWarnings("unchecked")
    List<List<V>>             cycles0    = ecs.getElementaryCycles();

    // remove cycles of size 2
    Iterator<List<V>>         listIt    = cycles0.iterator();
    while(listIt.hasNext()) {
        List<V> cycle = listIt.next();

        if(cycle.size() == 2) {
            listIt.remove();
        }
    }

    // remove repeated cycles (two cycles are repeated if they have the same vertex (no matter the order)
    List<List<V>> cycles1             = removeRepeatedLists(cycles0);

    for(List<V> cycle : cycles1) {
        System.out.println(cycle);    
    }


    return cycles1;
}

private void buildAdjancyMatrix() {
    Set<DefaultEdge>     edges        = this.graph.edgeSet();
    Integer             nVertex     = this.vertexList.size();
    this.adjMatrix                     = new boolean[nVertex][nVertex];

    for(DefaultEdge edge : edges) {
        V v1     = this.graph.getEdgeSource(edge);
        V v2     = this.graph.getEdgeTarget(edge);

        int     i = this.vertexList.indexOf(v1);
        int     j = this.vertexList.indexOf(v2);

        this.adjMatrix[i][j]     = true;
        this.adjMatrix[j][i]     = true;
    }
}
/* Here repeated lists are those with the same elements, no matter the order, 
 * and it is assumed that there are no repeated elements on any of the lists*/
private List<List<V>> removeRepeatedLists(List<List<V>> listOfLists) {
    List<List<V>> inputListOfLists         = new ArrayList<List<V>>(listOfLists);
    List<List<V>> outputListOfLists     = new ArrayList<List<V>>();

    while(!inputListOfLists.isEmpty()) {
        // get the first element
        List<V> thisList     = inputListOfLists.get(0);
        // remove it
        inputListOfLists.remove(0);
        outputListOfLists.add(thisList);
        // look for duplicates
        Integer             nEl     = thisList.size();
        Iterator<List<V>>     listIt    = inputListOfLists.iterator();
        while(listIt.hasNext()) {
            List<V>     remainingList     = listIt.next();

            if(remainingList.size() == nEl) {
                if(remainingList.containsAll(thisList)) {
                    listIt.remove();    
                }
            }
        }

    }

    return outputListOfLists;
}

}
Community
  • 1
  • 1
Jose Ospina
  • 2,097
  • 3
  • 26
  • 40
3

I'm answering this on the basis that you want to find chordless cycles, but it can be modified to find cycles with chords.

This problem reduces to finding all (inclusion) minimal paths between two vertices s and t.

  • For all triplets, (v,s,t):
    • Either v,s,t form a triangle, in which case, output it and continue to next triplet.
    • Otherwise, remove v and its neighbor except s and t, and enumerate all s-t-paths.

Finding all s-t-paths can be done by dynamic programming.

Pål GD
  • 1,021
  • 8
  • 25
  • 1
    Thanks for the answer, I am a litle lost anyway. This is how I am interpreting your answer: Let A and B in the graph above be s and t in your algorithm, then: 1) let C be v, no triangle, remove C and H, paths from A to B are {A-B,A-F-D-E-B,A-F-G-E-B}. 2) let D be v, no triangle, remove D, C, F, and E, paths A to B are {A-B}. 3) Let E be v, no triangle, remove E, D and G, path from A to B are {A-B}.... and so on... when do I find the cycles? – Jose Ospina Jan 04 '13 at 15:34
  • 2
    s,v,t in my example were *consecutive* vertices in a cycle. If you remove v from the graph and find a path from s to t, then by adding v, you obtain a cycle. In your example, let s=A, v=B an t=C. Now, if you remove v=B from your graph and find paths between s=A and t=C, you get cycles when you add v=B back to the graph. – Pål GD Jan 05 '13 at 09:35
  • So, as you mention, I first choose s=A, v=B and t=C, remove B and E and H, find only one path from A to C: {A-F-D-C}. (Three cycles are still missing so I am assuming I need all possible consecutive triplets starting from A), so I then choose s=A, v=B and t=E, remove B, C, and H, paths from A to E are: {A-F-D-E,A-F-G-E} two more cycles found, nice. Then, for s=A, v=B and t=H, no paths from A to H. Then, for s=A, v=F and t=D, remove F and G, paths from A to D are: {A-B-C-D}, {A-B-E-D} (ups, repeated cycles, how do I notice it?).... Probably I am missing something else now..... peace – Jose Ospina Jan 05 '13 at 18:13
  • Thanks for the answers, I understand that your theory is right but I was looking for some library or algorithm that could be directly implemented. You leave a large gap because of the _Finding all s-t-paths can be done by dynamic programming_. I finally used existing code for directed graphs with few modifications to handle undirected graphs. – Jose Ospina Jan 13 '13 at 15:48