Cycle Detection in Graph

33 views
Skip to first unread message

Amit Kumar Mondal

unread,
Sep 12, 2016, 6:19:50 AM9/12/16
to JointJS
Hello all,

I am trying to detect existence of cycles in a JointJS directed graph. I tried the following approach:

           function checkForCycleExistence() {

              var visited = [];

              var level = 0;

              var isCycleExists;

              var _elements = graph.getElements();

             for (var i = 0; i < _elements.length; i++) {

                   var elem = _elements[i];

                       if ((graph.getPredecessors(elem).length > 0) && !elem.isLink()

                                 && hasCycle(elem, visited, level)) {

                           isCycleExists = true;

                          break;

                 }

              }

              if (isCycleExists) {

                   top.jsniShowCycleExistenceError();

              }

              return isCycleExists;

          }

     

        function hasCycle(comp, visited, level) {

              var neighbors = graph.getNeighbors(comp, {

                     outbound : true

        }), i;


                if (visited.indexOf(comp.id) > -1)

                     return true;

           visited.push(comp.id);


                for (i = 0; i < neighbors.length; i++)

                 if (hasCycle(neighbors[i], visited.slice(), ++level))

                          return true;


                return false;


        }


I tried it with many examples and it seems it can find cycles in most of the graphs except in some trivial ones where the graph does not contain any cycle. For instance, 
A--->B, A--->C, C--->D, D--->B
or 
A--->B, A--->C and C--->B

It would be really helpful if anyone can help me in this.

Amit Kumar Mondal

unread,
Sep 13, 2016, 3:31:33 AM9/13/16
to JointJS
Reply all
Reply to author
Forward
0 new messages