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.

Similar Messages

  • 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 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

  • 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

  • Any way to find the % of cycles a thread is using?

    without using a debugger or profiler,
    is there any way i can find out how many cycles my thread is active between two timestamps?
    or any way to find out the percentage of cycles my thread is active (compared to other threads)?

    oi, using native code is one of the main things i'm
    trying to avoid :) is there a way to find a threads
    CPU usage, or percentage thereof without having to use
    native code?There is no java api. So that means it is OS specific. You can't identify a specific thread using a process (via Runtime.exec) so that means the only solution is to use JNI.

  • I just upgraded my iPad from 4.3.3 to the newest - I think 6.1.3.  I cannot find my photos and videos.  I tried a restore, but after 3 hours, it's timing out.  Pardon my ignorance on asking this question; but is there a way to find my photos?

    I just upgraded my iPad from 4.3.3 to the newest - I think 6.1.3.  I cannot find my photos and videos.  I tried a restore, but after 3 hours, it's timing out.  Pardon my ignorance on asking this question; but is there a way to find my photos?  I do nto care about anythign else.
    Here are the steps I though I took this morning:
    Backup iPad
    Connect to iTunes and downlaod newest version of iTunes and then newest iOS
    restart Vista Laptop
    upgrade to newest iOS
    I knew somethign was wrong when it took about 6 hours to upgrade the iPad
    at the end it errored with this message error (-50), but the upgrade worked
    I was expecting to see all my photos but didn't see them
    I have tried a restore to a back up 2 times.  The first time took 3 hours and just sort of timed out - it kept saying that there was an hour to go
    I tried it again 2 hours ago and same message.
    They are very valuable to me and so now I am panicking
    Your help is much appreciated

    Hi Eric Ferguson,
    Thanks for using Apple Support Communities.
    For troubleshooting on this, take a look at this article:
    iTunes: Specific update-and-restore error messages and advanced troubleshooting
    http://support.apple.com/kb/ts3694
    Error 13, 14, 35 and 50 (or -50)
    These errors are typically resolved by performing one or more of the steps listed below:
    Perform USB isolation troubleshooting, including trying a different USB port directly on the computer. See the advanced steps below for USB troubleshooting.
    Put a USB 2.0 hub between the device and the computer.
    Try a different USB 30-pin dock-connector cable.
    Eliminate third-party security software conflicts.
    There may be third-party software installed that modifies your default packet size in Windows by inserting one or more TcpWindowSize entries into your registry. Your default packet size being set incorrectly can cause this error. Contact the manufacturer of the software that installed the packet-size modification for assistance. Or, follow this article by Microsoft: How to reset Internet Protocol (TCP/IP) to reset the packet size back to the default for Windows.
    Connect your computer directly to your Internet source, bypassing any routers, hubs, or switches. You may need to restart your computer and modem to get online.
    Try to restore from another known-good computer and network.
    Best of luck,
    Mario

  • Is there a way to find where you imported files from?

    I imported a batch of photos from a wedding. Edited them all, and then I moved the original files from their native folder. This created the "This file is offline or missing" dialogue. I tried moving the files back but with no luck. I think I just forgot where they were originally at.
    So, my question is, is there was a way to find out which folder you imported the files from so I can put them back in place and export them without losing a weeks worth of edits?
    Thanks,
    Cody

    If you left click on the question mark it will throw up a dialogue (a) advising you that the file is missing (b) show you the last location it was located and (c) offer you the option of pointing LR in the direction of where the image can be found. Often, when LR is given the new location for one image it manages to do the rest.
    The alternative is to right-click on the top level folder in the libraries left hand panel and choose 'locate folder'. Again, once the top level folder has been located LR usually updates the sub folders.
    When moving folders etc around it is better to do this from within LR itself therebye preventing these sort of problems.

  • Last invoice activity/Date in SAP- Any way to find out??

    Hello,
    Want to know if there is any way to find the last invoice date  per vendor in SAP. Is there any field in the table  that can give us the last activity of the vendor.
    Thanks,
    Riya

    Hi
    If it is a logistics invoice, you can get the information from table RBKP, where the entry date and time is stored for each invoice.
    If you are looking for invoice directly posted in FI, you can use the same logic and can extract it from BKPF table by filtering based on document type.
    Regards

  • Is there a way to find out which transactions are called by first transacti

    I'm trying to find out if there is a way to find out for ex:
    You go to PFCG and put in transaction CO15
    What other transactions is CO15 going to need or call.
    Thanks
    Joe

    In your test or QA environment, use ST01 to start a trace for authorization checks.  Execute CO15 as you normally would using options on the screen to enter the production order confirmation.  Once complete, stop the trace and review the log.  the log will include all authority checks that occurred.
    Another response was to use the USOBT table.  You can call these tables directly using SU24.  the check maintain entries are validate when an authority check is executed.

  • Is there a way to find the number of downloads of music from itunes store?

    Hi,
    Is there any way to find the number of downloads of each music file available on itunes store. If not exact no of downloads but atleast a relative term to find the rank of the music track From any API
    Thanks
    Sandeep

    A: Is there a way to read the number of active sequence executions from the Engine?

    Scott,
    > One way of handling the issue of init once a set of instruments is to
    > create a new sequence file that has a sequence to init and a sequence
    > to close the instruments. Assuming that you always terminate a
    > sequence and do not abort them, you could add a ProcessSetup and
    > ProcessCleanup callback sequences to the client sequence file that
    > using these instruments. These callbacks are automatically called by
    > the process model in both the Single Pass and Test UUTs execution
    > entry points. The callback sequences could call the init and close
    > sequences for the hardware. In the hardware sequence file you could
    > reference count the number of execution that init and close by setting
    > the file globals in the sequence file to be shared across executions
    > and then add a numeric value that keeps track of references for the
    > instruments. The init sequence adds to the count, and the close
    > sequence subtracts from the count. The init sequence inits the HW if
    > the count is 0->1 and the close sequence closes the HW if the count is
    > 1->0.
    >
    > This is one of many ways in TestStand that this could be done, not to
    > mention that this could also be done in a similar way in a LabVIEW VI
    > or DLL directly.
    That sounds like it will work. I'll try adding a client count
    increment/decrement in the DLL initialize and terminate functions. This
    should essentially perform the same tasks as the callback scheme you mention
    above, no?
    The reason I didn't think the 'client counting' scheme would work initially
    was I mistakenly thought that the termination function would not get called
    under Terminate conditions. Since Terminate conditions happen a LOT during
    our initial debug of new UUT types, I didn't think that would be acceptable.
    I forgot that lacing the terminate funciton in a cleanup step group, I can
    force it to be called in Terminate conditions.
    > If you abort an execution then the reference counting idea above would
    > fail to decrement properly. That might b... [Show more]

    Read other 5 answers

  • Is there any way to find out a Tcode used by user in a particular interval.

    Hi
    Is there any way to find out a Tcode used by user between 10/8/2009 to 31/8/2009, in production?
    Satish.

    Yes i have been trying SE16N only. But i am unable to pull data based on dates (Aug/8 to Aug 21)... its showing list of users who have accessed the tcodes directly for entire month....
    Se16n ->Export mode->month->08/2009
      --->     Transacction profile -->Standard
    I want to find out only users who have used a particular tcode during those dates.....in august..
    Satish

  • Is there a way to find the class objects memory size?

    Hi Friends,
    Please help.
    Is there a way to find the number of Objects created and total size?
    For example:
    class AgeRecord
    int start;
    int end;
    AgeRecord(int start, int end)
    this.start = start;
    this.end = end;
    In a loop if I create 1000 objects, how will I get the total memory size
    Thanks and Regards
    JG

    You might find this useful...
    package forums;
    http://weblogs.java.net/blog/dwalend/archive/2007/11/the_thing_about.html
    http://forums.sun.com/thread.jspa?threadID=457279&start=30&tstart=0
    http://www.velocityreviews.com/forums/t364574-size-of-boolean-type.html
    The JLS doesn't specify the size of a boolean, leaving it upto the JVM
    implementor to define. Sun's JVM stores booleans as:
    (1) a boolean is-an int; i.e. a signed 32 bit twos-compliment integer.
        At face value, this is an innordinate waste of space, but Java uses a
        32-bit stack frame, and most (modern) CPU's use a 32-bit word anyway,
        so the wasted space is worth the CPU cycles, and it's simple.
    (2) a boolean[] is-a byte array, using 1 byte per element, rounded up to the
        nearest 8, plus 8 bytes for the array-object itself.
        For example: boolean[] bools = boolean[100];
        100 mod 8 = 4; so that'd be 104 bytes + 8 bytes = 112 bytes.
        So, let's dis/prove the contention by experiment.
        1,000,000 mod 8 = 0 so 1,000,000 + 8 bytes for the array = 1,000,008
    class BooleanArraySizeTest
      public static void main(String[] args) {
        final Runtime rt = Runtime.getRuntime();
        System.out.println("The contention is that each iteration should use 1,000,008 bytes.");
        try {
          long before, after;
          final int TIMES = 32;
          boolean[][] bools = new boolean[TIMES][];
          for (int i=0; i<TIMES; i++) {
            before = rt.totalMemory() - rt.freeMemory();
            int n = 1000*1000-(TIMES/2)+i;
            bools[i] = new boolean[n];
            after = rt.totalMemory() - rt.freeMemory();
            System.out.print(n);
            System.out.print('\t');
            System.out.print(after-before);
            System.out.println();
        } catch (Exception e) {
          e.printStackTrace();
    999984 used=1000000 bytes
    999985 used=1000000 bytes
    999986 used=1000000 bytes
    999987 used=1000000 bytes
    999988 used=1000000 bytes
    999989 used=1000008 bytes
    999990 used=1000008 bytes
    999991 used=1000008 bytes
    999992 used=1000008 bytes
    999993 used=1000008 bytes
    999994 used=1000008 bytes
    999995 used=1000008 bytes
    999996 used=1000008 bytes
    999997 used=1000016 bytes
    999998 used=1000016 bytes
    999999 used=1000016 bytes
    1000000 used=1000016 bytes
    1000001 used=1000016 bytes
    1000002 used=1000016 bytes
    1000003 used=1000016 bytes
    1000004 used=1000016 bytes
    1000005 used=1000024 bytes
    1000006 used=1000024 bytes
    1000007 used=1000024 bytes
    1000008 used=1000024 bytes
    1000009 used=1000024 bytes
    1000010 used=1000024 bytes
    1000011 used=1000024 bytes
    1000012 used=1000024 bytes
    1000013 used=1000032 bytes
    1000014 used=1000032 bytes
    1000015 used=1000032 bytes
    ENVIRONMENT:
      Microsoft Windows [Version 6.0.6000]
      Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
      C:\Users\Administrator>java -version
      java version "1.6.0_12"
      Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
      Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
    */Cheers. Keith.

  • I just got a text from verizon stating  a 3rd party vendor just charged to my bill.  Is there a way to find out the cost of the charge.

    Is there a way to find out what a 3rd party vendor charged to my bill, before the end of the billing cycle.

    You could try calling CS, but other than that I don't think there is.

  • Find development that was directly done in production

    guys,
    i suspect that some of my developers were doing development directly in production because the client and system were open. How can i find a list of objects that they modified directly there -- both SAP standard and custom ?
    I was thinking about looking at all the transport requests from se09 but that wouldnt cover objects that were saved in $TMP package ??? So any way to find out all ?
    also, any idea about how to find the same for all the customizing that was directly done in production ?
    regards,
    VM
    Moderator message: please get your system landscape in order, search for available information before asking.
    Edited by: Thomas Zloch on Feb 23, 2011 12:11 PM

    Yes, but this is basic stuff which you've been hammering the forums with for the past several weeks.  You should not be using these forums as a consulting service for your own consulting work...

  • What is a clever way

    To avoid cfquery timeout errors?
    Note: I can't do anything to make my db or server faster because its hosted
    I am looking for a CF solution to avoid throwing the user a timeout error (which presents them with a custom error page).  What I'd like to do is have some logic try to reload the page x amount of times if it hasn't loaded in say... 20 seconds.
    Any ideas?

    I doubt you'll find a clever way, since this is a not-clever problem.
    You could try something like this:
    <cfset keepGoing = true>
    <cfset counter = 1>
    <cfloop condition="#keepGoing#">
    <cfset counter = counter +1>
    <cftry>
    <cfquery...>
    <cfset keepGoing = false>
    <cfcatch>
    <!--- so you don't keep trying forever -->
    <cfif counter eq 3>
      <cfset keepGoing = false>
    </cfif>
    </cfloop>
    <cfreturn queryVar>
    Definitely not pretty, but it would achieve part of what you want, which is to keep trying. IT does not achieve clever, because it's kind of a dumb problem to have ... sort of like the rats in "Bad Boys II" that keep eating the drug dealer's money: "It's a stupid problem to have, but it's  a problem nonetheless".
    Good luck!

Maybe you are looking for