Finding Cycles in a Graph

Can anybody help me with an algorithm to detect cycles within a graph? or at least give me some direction on how to write a program to find all cycles in a graph. I have been stuggling to find something in vain.
Thanks,
Rexland

Can anybody help me with an algorithm to detect
cycles within a graph? or at least give me some
direction on how to write a program to find all
cycles in a graph. I have been stuggling to find
something in vain. There's probably good reason for that, in general, this is an intractable problem. For dense graphs, the number of cycles increases faster than the factorial of the number of vertices. More details of your problem will probably result in better answers.

Similar Messages

  • Clever way to find cycles in a directed graph

    I need to find cycles in a graph.
    I can think of a way to do it recursively: i go down every path, keep track of previous nodes, and when i visit a node in my history, i have a cycle.
    what im curios is if you guys know a better way to do this?
    yes i have googled this before asking.

    No, DFS is optimal. However, you need to think about whether you want to find every cycle, because that becomes very expensive very quickly in a graph with high connectivity.

  • Finding cycles in an undirected graph.

    I've been trying to implement my own graph class, and one of the things I would like to do is do a DFS to find cycles.
    So far I've been able to write this and I'm pretty confident it works:
         static boolean findCycle(){
              LinkedList<Node> queue = new LinkedList<Node>();
              unEnqueue();
              Node start = graph.getFirst();
              start.visited = true;
              queue.push(start);
              Node previous = new Node();
              previous = start;
              while (!queue.isEmpty()) {
                   Node node = queue.pop();
                   node.visited = true;
                   System.out.println("previous is "  +previous);
                   for (Node neighbor : node.neighbours) {
                        if(!neighbor.visited){
                             queue.push(neighbor);
                        }else if(allVisited()){
                             return true;
                        }else if (neighbor.visited && neighbor == start){
                             unVisit();
                        }else if(neighbor.visited && neighbor != previous){
                             System.out.println("neighbor is "+ neighbor);
                             return true;
                   previous = node;
                   System.out.println("previous is " +previous);
              return false;
         }Visited is just a boolean value each node has.
    unVisit takes our graph and resets all visited values to false.
    After this returns I check each node and list those that are visited - these nodes constitute my cycle.
    This returns the nodes out of order (not in the order they are listed) which is fine.
    It also breaks if there is no cycle in the graph.
    Can anyone think of how to correctly return false? Or, maybe a graph that would break this?
    Thanks

    Thanks for the reply. I've found some inputs where my algorithm doesn't work so I suppose I should back up and ask a new question:
    Is it possible to do a DFS iteratively like I am, find the path of nodes that represents a cycle and then return that? The main problem I run into when doing these sorts of things is that since the graph is undirected the DFS likes to yield cycles of the first two nodes that are connected. Another issue is that since I only have the nodes and their neighbors there really aren't edges to iterate through and mark as back, cross etc. Is it possible to use a hashmap to store the path?
    Let me know if I need to clarify things further
    Also: I didn't return a cycle before because the cycle was represented as all nodes that had their boolean visited set to true. I could print the list simply by iterating through the graph and printing which nodes had a true visited boolean.
    Edited by: Blitzkev on May 17, 2010 6:24 PM
    Edited by: Blitzkev on May 17, 2010 6:27 PM
    static LinkedList<Node> findCycle(LinkedList<Node> g){
              Stack<Node> s = new Stack<Node>();
              HashMap<Node,Node> hm = new HashMap<Node,Node>();
              LinkedList<Node> cycle = new LinkedList<Node>();
              boolean done = false;
              unMark(g);
              unVisit(g);
              s.push(g.getFirst());
              Node currNode = null;
              while (!s.isEmpty() && !done) {
                   currNode = s.pop();
                   currNode.visited = true;
                   for (Node neighbor : currNode.neighbours) {
                        if( !neighbor.visited && neighbor.marked == 1 ) {
                             hm.put(neighbor, currNode);
                             Node n = neighbor;
                             do {
                                  cycle.add(n);
                             } while( (n = hm.get(n)) != neighbor && !cycle.contains(n) && n != null );
                             done = true;
                             break;
                        if( !neighbor.visited ) {
                             s.push(neighbor);
                             neighbor.marked = 1;
                        hm.put(neighbor, currNode);
              return cycle;
         }I got it working with a hashmap.
    Edited by: Blitzkev on May 17, 2010 6:48 PM

  • When using suggestedItems or LOV (on the same field) I get " Graph nodes cannot be sorted due to a cycle in the graph."

    Hi. I am on Jdev 11g R2
    I have a atribute in the VO with LOV attached. And also another attribute in the same LOV with is dependant to the first LOV. It means when I choose LOV on the first attribute the second LOV uses the chosen value,
    I droped the VO as FORM on the page.
    When I go to the first attribute and choose the LOV value (from suggestedItems or from LOV search popup) I get the following message:
    Graph nodes cannot be sorted due to a cycle in the graph
    It only happens for the first time. If i choose LOV after I get the error message , everything is working just fine
    Error message indicates that it may be some loop in the VO, but there is no....
    Please advice what can it be

    please post more log by turning on logging -
    http://xmlandmore.blogspot.in/2009/06/turn-on-diagnostic-to-debug-oracle-adf.html

  • How to find inflection point in graph when dx is very small

    Hello,
    I'm trying to sort through position data from a feedback pot to calculate linearity of movement as part of a testing procedure. An image of the data is attached. I want to delete all data in the 'flat' part, in order to do a linear fit and R^2 of the sloped line.
    This is made trickier by the fact that the number of samples, the start and end points, and slope of the line can all vary considerably. Therefore I need some way to find the 'knee' in the graph and remove all subsequent samples from the data. 
    The most obvious method I tried was to use a derivative to find the inflection point, but since I have so many data points, the dx is very small
    (~0.05) when using the built-in labview derivatives. This means that I can't distinguish the inflection point from any other change in the values due to noise or change in velocity. I made my own derivative function, which was a newton quotient that looked at (xi+N)-(xi-N) instead of (xi+1) - (xi-1), but this still did not give good results. My next idea is to just look at the difference of every N points, and arbitrarily decide a threshold to indicate when it has levelled off. Any other ideas would be really helpful though.
    Thanks,
    -SK-
    Attachments:
    position.PNG ‏17 KB

    Lets see if I can answer without having to write a book.
    Fisrt I'd run the data through a zero-phase shift low pass filter. Then look at the 2nd derivative to find the knee. Using a zero-pahse shift fileter I was able to detect when a value was jumping up when it started to jump rather than after. THis thread may be interesting.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Java in finding peaks of a graph.

    I wrote a program to read a file containing datapoints using RandomAccessFile and then find the peak value by comparing each y value.
    String ntr = ((String)raf.readLine()).substring(5);
    System.out.println(ntr);
    d [j] = Double.parseDouble(ntr);
    if (d [i][j-1]<d [i][j] && d [i][j+1]<d [i][j]){
    peak [i] = d [i][j];
    l = raf.getFilePointer();
    System.out.println(peak [i]);
    I get the following compilation error.
    Can't make a static reference to nonstatic variable d in class Plot
    d [i][j] = Double.parseDouble(ntr);
    ^
    Please help me to find out where the problem in the code is.

    Thank you. But now there is a following runtime error.
    Exception in thread "main" java.lang.OutOfMemoryError
    at Plot.<clinit>(Plot.java:4)
    Why is the JVM not allocating memory to this program?

  • Finding peak value on graph

    I am trying to create a program for students (young kids 6-12) where they would be able to strike a copper pipe of various length then the sound would be taken and plotted by labview. From the plot I am having a hard time to find a way to record the peak value; is there anyway that labview displays the peak value?

    I have attached an updated VI. I am trying to set the program up to where a sound is taken, when a pipe is struck, and plotted in the frequency domain. From which it can be determined the max (peak frequency) when i get that all sorted out I will add or let hem use excel to plot peak frequency of 5 or more pipes vs length and set a best fit line to find a function that will allow them to find the length of the pipe knowing the frequency needed.
    Attachments:
    windchime.vi ‏104 KB

  • Finding all cycles in a directed graph

    Hi all,
    I have a task I believe I will solve relatively easy if I manage to detect all cycles within a graph that I can build from the data given.
    I googled for a while but I couldn't find some explanation that I can use. I came upon refrerences to some publication referred as "Reingold, Nievergelt and Deo 1977", however I could not find some online resources from that ?book?.
    AFAIK I can detect whether thre is a cycle using DFS, but I need all cycles.
    Please guide me to some online resource that can help me find a suitable algorithm, or if you know such algorithm please post its name so I can find information about it.
    Thanks for your cooperation
    Mike

    Thanks for all those replies!
    I still haven't implemented a solution and I have some questions. I googled and skimmed through a book I have and I came up with the definition that topological sorted graph means that all 'paths' lead in one direction (such ordering of the vertices V that for each edge(i, j) in E vertex i is to the left of vertex j).
    If I understand correctly your idea, it is to first order the vertices by some criterion and then remove all edges leading in a direction opposite to the sorting direction.
    I am not quite sure I understand correctly how to choose the ordering of the vertices. In the beginning of the sorted vertex list we must have vertices with the most possible outgoing edges /as sum of weights/ and least incoming(because these are to be removed), did I understand the idea correctly?
    I thought about another solution but I cannot estimate how heavy it will be as processing time: to perform search(maybe DFS) and if I find a cycle - to remove the least heavy edge and continue the search from the position before passing this edge.
    I guess it is not applicable since it can escalate to a very time-heavy task, especially if each time we go back.
    So I think I will implement the Idea YATArchivist proposed - sorting vertices and removing back-edges, and we'll see what will happen. After all - it's only a contest, I can only win or not win, there are no losers ;)
    Thank you for giving your valuable time for sharing thoughts in this thread
    Mike

  • Detecting Cycles in a Directed Graph

    Can somebody help me how to find cycles in a directed graph,
    I already made a Depth First Search code and base on what I've learned Cycles can be done using Depth First Search
    public static void DFS(int numberNodes){
        System.out.print("Enter starting node for Depth First search: ");
            int v = scanner.nextInt();
        for(int i = 1;i<=numberNodes;i++)
                 visited[i] = false;
            dfs_rec(v,numberNodes);
        }//end DFS()
         public static void dfs_rec(int v,int n){
        int i;
        visited[v] = true;     
             System.out.print(" "+v);
             for(i = 1;i<n;i++)
                  if(adj[v] == 1 && visited[i] == false)
                   dfs_rec(i,n);
         }//end dfs rec                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    malcolmmc wrote:
    paulcw wrote:
    I don't see the need for unsetting the flag. Visited is visited. What needs to be added is to respond when the flag is set to true.You need to clear the flag because the same node might be reached through more than one route without the graph being cyclic (it could be a shared sub-tree).
    Only if you encounter a node which is already part of the path you're examining have you found a loop.But not if it's a depth-first search, no?
    Oh, I see what you're saying. Set the flag, do a depth-first search, then when you exhaust that and do a sibling, clear the flag. OK.

  • Finding Indegree of Node

    Given a directed graph, I need to determine if there is a directed cycle. If so, print one out. Otherwise print out a topological order.
    So I have created a class Node class and SymbolTable (i.e HashMap) that keeps track of all the nodes and who they are pointing too.
    private SymbolTable st = new SymbolTable();
          * helper data type for adjacency lists
         private static class Node {
              String name;
              Node next;
              void insert(String v) {
                   Node x = new Node();
                   x.name = v;
                   x.next = next;
                   next = x;
              }Each time there is a vertex from v to w I added that information into the node with the corresponding keys that have all the nodes its connected too.
         public void addEdge(String v, String w) {
              if (st.get(v) == null) addVertex(v);
              if (st.get(w) == null) addVertex(w);
              Node adjlist = (Node) st.get(v);
              adjlist.insert(w);
         } My problem is that I a having trouble finding the indegree of the vertex in order to determine the topolgical sort of the graph. I tried to reverse engineer my outdegree method however I cant seem to figure out how to determine how many vertexs are point to a certain vertex.
    Here is the code I am trying to use:
    public int indegree(String v) {
              int deg = 0;
              Node adjlist = (Node) st.get(v);
              for (Node x = adjlist.next; x != null; x = x.next)
                   if (x.next == null)
                        deg++;
              return deg;
    }Is there a better way to develop a topological order of vertex and determining if there is a cycle within the graph or anyone have a solution to finding the indegree of a vertex?
    Thanks In Advance

    I've been staring at your code for a couple of minutes now, but I don't
    understand your code, especially the methods in nested Node class
    don't make sense to me ...
    This is how I would build a Node class:public class Node {
       private int inDegree= 0;
       private Set edges= new HashSet();
       private String name;
       // ctor:
       public Node(String name) { this.name= name; }
       // set an outgoing edge
       public void setOutEdge(Node w) {
          if (edges.get(w.name) == null) {
             w.inDegree++;
             edges.add(w.name);
    }If an edge from a Node v to another Node w is set, node v takes care
    of the inDegree of node w and updates its own edges set. Note that
    using a set assumes a proper graph, i.e. not a multi graph where more
    than one edge can connect nodes v and w.
    kind regards,
    Jos

  • How do i plot with the operating system time in one plot and show lines between cursors in another using the same XY graph?

    I am having some trouble graphing two plots at once. One plot is to show the current temperature inside a chamber as a function of time. I am trying to pick the current time and temperature each second and plot it with each point being connected by a line. I am able to show a moving, blinking dot each second but I can't figure out how to develop an actual line with these dots. To make matters worse, the blinking dot is back in the year 1903. I understand that it uses seconds elapsed since 1903, and am trying to find out how to graph the current temperature with the system time.
    The second plot is just 5 moveable cursors that are to be connected by a line. I am able to move the cursors and retrieve the position information, but I can't make a line between them.
    I have attached my main .vi, though you may have to pick the graphing part off to have it work for you.
    Attachments:
    Main Module Chamber Testing I_O every 30 sec.vi ‏288 KB

    You're not creating the XY graph data correctly. I've attached an example with a couple of simple XY Graphs. One is using a couple of shift registers to hold the spearate x and y arrays. I think this is what you were trying to do. The other one uses a VI from the shipping examples called XY Chart. It makes an XY Grpah act like a chart. I've also shown the correct way to display current time.Message Edited by Dennis Knutson on 05-12-2005 03:51 PM
    Attachments:
    XY Graph.vi ‏41 KB

  • BI GRAPHS IN ORACLE FORMS 10G

    AFTER FINDING SOLUTION TO MAKE GRAPHS CUSTOMIZATION IN ORACLE FORMS 10G, I was suggested to use BIGRAPH so installed all package(formsgraph.jar and whole demo package) and I configured properly all my files. But graph.fmx which exist in demo when run on browser does not display any graph on bean area it might be as no data retreived or data not populated due to bug in fmb . I made new temp.fmb by only creating single item and bean on canvas. On validating item I wrote following syntax.
    BEGIN
         IF (:BLOCK1.TEXT_ITEM5 = ' ') THEN
         message('validating');     
         set_custom_property('block1.BeanArea1',1,'GRAPHTYPE','HORIZONTAL_BAR');
    set_custom_property('block1.BeanArea1',1,'ENABLE_TOOLTIPS','ALL');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'SET_DELIMITER',',');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','Europe,Sales,25000');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','USA,Sales,70000');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','Europe,Taxes,2500');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','USA,Taxes,2500');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','Europe,Savings,22500');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','USA,Savings,67500');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_DATA_TO_GRAPH','');
    SET_CUSTOM_PROPERTY('block1.BeanArea1',1,'ADD_ROWDATA','UK,Taxes,67500');
    set_custom_property('block1.BeanArea1',1,'SHOW_GRAPH','');
         END IF;
    END;
    Still surprise as forms open successfully on Web browser but no chart displayed. I am really fade up as I required lot of time to install demo version in my original oracle 10g software. My boss say how can new version have no features of graphics. I can not tell or say to buy that oracle graphics are customized in Oracle 11g.
    If anybody have solution for above, please reply.
    Thanks,
    Prashant

    Hello Omama,
    Problem of Bi Graphs have been solved by running url with extension as config=Bigraph. For my next problem in graph of 10g I am going to post new thread as BI Graphs does not serve my problem. Anyway Thanks.
    Regards,
    Prashant

  • WCS not graphing CleanAir Interferers

    I have WCS managing 4 controllers.  1 of which has clean air enabled.  WCS gives air quality reports just fine, but it gives me no information on the Device Interferers or the Interferer count.  I can go to the controller, go to monitor>cleanair and look at the APs that find interferers and then graph the data to show bluetooth, microwaves, continuous transmitters etc, but why is this info not seen in WCS?

    From WCS config guide :
    te
    The  information in the worst interferer and interferer count charts is  collected from Mobility Services Engines (MSE). If MSEs are not  available, this chart will not show any results."
    http://www.cisco.com/en/US/docs/wireless/wcs/7.0MR1/configuration/guide/wst.html#wp1168776

  • Buil-in microphone frequency response graph

    I'm curious as to where I can find a frequency response graph for the built-in mic in the 15" MBP 2.8. I know it's a silly thing to want, but... Sometimes I don't have the time or resources to set-up an external mic with a flat frequency response, and would just like to use the built-in mic very quickly to "EQ" or "ring out" rooms. I can't find the info on the built-in mic anywhere. Any suggestions?

    Have you ever used the microphone? Have you ever actually used a laptop to do this?
    I don't have a graph, but from years of working with audio I can tell you that it doesn't have the frequency response, sensitivity and directionality to do what you want.
    A nice external mic and portable interface like the iMac would not only do a better job but would look a lot more professional than running around trying to point the cheap microphone of a laptop in the right direction.

  • Accessing properties of multiple graphs

    Hello, I have a VI with over 100 different graphs.  And many times, I want to access a property node for each one, and make the same changes.  How would I set up a "For" loop that will cycle through each graph?  I see that one is named xy graph 1, xy graph 2, etc.  So this seems like I could plug that number in from the loop counter, but I don't see how to do it.
    Thanks,
    Pat

    pwalsh wrote:
    Hey, thanks, I'll look into the sub VI approach.  That's something I've not done before. 
    Do you know how to generate an array of references to all the front panel objects?
    It's not exactly clear who you're responding to, but the VI I posted will (in theory anyway. It was written quickly and may have bugs) generate an array of references to all the controls on the FP (not including tabs and clusters). If you want to use it as a subVI (which is a very good idea), you need to use a Panel refnum control instead of the property node (just right click and create a control), set the connector pane and an icon and you're done.
    To learn more about LabVIEW, I suggest you try searching this site and google for LabVIEW tutorials. Here and here are a couple you can start with. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide and the LabVIEW user manual (Help>>Search the LabVIEW Bookshelf).
    Try to take over the world!

Maybe you are looking for