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.

Similar Messages

  • 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

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

  • A problem about the compression of directed graphs

    Right now I encountered a problem in my research that is about graph compressing (or contraction, etc.). I've searched in various ways for existing techniques on this problem and found nothing. I've been trying to figure out this problem by myself. However I would also like to seek some advice from you guys.
    The description of this problem:
    Given a directed graph G = (V, E) where V is the set of vertices and E
    is the set of directed edges. These vertices and directed edges
    represent the events and the directional relationships between pairs of
    events. Each edge is associated with a weight (or confidence score)
    which indicates the degree of the relationship. Now I want to compress
    the graph by merging some of the vertices into one superior vertex,
    which implies that several lower-level events are merged into one
    high-level event (this is mainly because the extent of news events
    defined are usually flexible). After that we can reorganize the
    vertices and edges and repeat this process until the size of the graph
    reaches a certain limit. Purely looking from the point of graph theory,
    is there any existing graph algorithm that solves this problem? As far as I have searched, the answer seems to be negative.This seems to be an interesting novel problem which falls in the area of graph algorithms. Could you suggest anything? Attached is a sample directed graph of such a kind which may be interesting.
    Check this URL to find out more about this kind of DAG:
    http://ihome.cuhk.edu.hk/~s042162/2005-05-24.jpg
    Thank you very much for your time and help.
    Regards,
    Daniel

    Sounds like an interesting problem. The temporal aspect presents an interesting wrinkle. Graph models have been becoming popular for the standard clustering problem recently, but they are typically undirected formulations. The idea of compressing a graph reminded me of work done by G. Karypis and V. Kumar on graph partitioning, some of their papers are available here:
    http://www-users.cs.umn.edu/~karypis/publications/partitioning.html
    SImilar to the reference given by matfud, with the additional restriction that there may be a size restriction on the size of the partitions or there may be multiple partitions (both restrictions make the problem NP-complete, IIRC).
    There's also the area of spectral graph partitioning which may be of interest. Its a way of finding relatively dense areas in a graph by using the eigenvalues of the adjacency matrix. Most of the results in this area are dependent on the fact that adjacency matrices for graphs are symmetric and semi-definite, which wouldn't be the case for a directed graph, but could be worth some experimentation if you have MATLAB or something similar.
    There's something else this problem reminds me of, but I can't think of it right now. Maybe later something will come to me.
    Good luck.

  • How to display a 'Directed Graph Structure' in ADF

    Hi
    I have a requirement where I have to display a 'Directed Graph Structure' (one with multiple nodes and links ). http://flylib.com/books/en/2.264.1.159/1/
    As of now there is no dvt component to support it.
    So I used a third party JS lib to draw the graph in HTML.
    Now I want to open this HTML page as pop in my adf application using JS.
    Please suggest me how to do that or any alternative way to display the graph structure.
    Thanks

    is there another way? or is it just not possible?
    gr
    Joeri

  • How to detect threshold voltage from xy graph?

    I am making labview program for analysing VI characteristic of diode. I want to show forwardbiased breakdown voltage automatically in xy graph or textbox. Is there any method for detecting breakdown voltage either through graph or some mathematical coding???

    Something like this?
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Threshold.png ‏12 KB

  • Directed graphs

    Help
    Having a problem with my directed graph, and its been frying my head. from the test that I've ran ita ppears to be working sort of the problem that I'm having is once I've created a node, I then attach an edge to that node, however where there are multiple edges it will only attach the last edge that it comes to. I'm creating a list of nodes, then trying to attach a list of edges to that particular node.
    code listing - theres a lot, sorry
    /////////////////////// edge class /////////////////////////
    //: Gedge.java
    /************************* Revision History *************************
    *     v1.0 - Initial version:
    public class Gedge implements IGedge{
         //labels for the edges
         private Object s, l;
         //nodes representing stations outbound and inbound
         private Gnode src, in, out;
         //linked list of edges
         private Gedge nextOutEdge;
         private Object o, i;
         * Default constructor Gedge
         * @param Gnode outbound:
         * @param Gnode inBound:
         * @param Object stationID:
         * @param Object lineName:
         public Gedge ( Gnode source, Gnode inDest, Gnode outDest, Object outBound, Object inBound, Object stationID, Object lineName ){
              o = outBound;
              i = inBound;
              s = stationID;
              l = lineName;
              src = source;
              in = inDest;
              out = outDest;
              //dest1 = null;
              nextOutEdge = null;
         }//end of constructor
         /////////////// Accessors ///////////////
         public Object getInBound() {
              return ( ( String ) i );
         }//end of getInBound
         public Object getOutBound() {
              return ( ( String ) o );
         }//end of getOutBound
         * @return
         public Object getLineName() {
              return ( ( String ) l );
         }//end of getLineBound
         public Object getStationID(){
              return ( ( String ) s );
         * @return
         public Gedge getNextEdge(){
              return nextOutEdge;
         }//end of getNextEdge
         * @return
         public Gnode getSource(){
              return src;
         }//end of getSource
         * @param newNextEdge
         public Gnode getInDest(){
              return in;
         * @param newNextEdge
         public Gnode getOutDest(){
              return out;
         * @param newNextEdge
         //public Gnode getDest1(){
         //     return dest1;
         /////////////// Transformers ///////////////
         public void setNextEdge( Gedge newNextEdge){
              nextOutEdge = newNextEdge;
         }//end of setNextEdge
         public void setInBound( Object inBound ) {
              i = inBound ;
         }//end of setDest
         public void setOutBound( Object outBound ) {
              o = outBound;
         }//end of setSource
         public void setLineName( Object lineName ) {
              l = lineName;
         }//end of setLineName
    }///:~
    ///////////////// end of edge class /////////////
    ///////////////node class////////////////
    //: Gnode.java
    /************************* Revision History *************************
    *     v1.0 - Initial version:
    public class Gnode implements IGnode {
         private Object id, name;
         private Comparable d;
         private Gnode nextNode;
         private Gedge firstEdge, nextOutEdge;
         private int outDegree;
         public Gnode ( Comparable data, Object stationName, Object stationID){
              d = data;
              id = stationID;
              name = stationName;
              outDegree = 0;
              nextNode = null;
              firstEdge = null;
              nextOutEdge = null;
         }//end of constructor
         /////////////// Accessors ///////////////
         public Object getID() {
              return ( ( String ) id );
         }//end of getID()
         public Object getStationName() {
              return ( ( String ) name );
         }//end of getStationName
         public Comparable getData() {
              return d;
         }//end of getData
         * @return
         public Gnode getNextNode(){
              return nextNode;
         }//end of getNextNode
         * @return
         public int getOutDegree(){
              return outDegree;
         }//end of incOutDegree
         * @return
         public Gedge getNextEdge(){
              return nextOutEdge;
         }//end of getFirstOutEdge
         * @return
         public Gedge getFirstEdge(){
              return firstEdge;
         /////////////// Transformers ///////////////
         public void setStationName( Object stationName ){
              name = stationName;
         }//end of setStationName
         * @param data
         public void setComparable( Comparable data ){
              d = data;
         }//end of setComparable
         public void setStationID(Object stationID) {
              id = stationID;
         }//end of setStationID
         * @param newNext
         public void setNextNode( Gnode newNode ){
              nextNode = newNode;
         }//end of setNextNode
         public void setNextEdge( Gedge edge ){
              nextOutEdge = edge;
         }//end of setFirstOutEdge
         public void setFirstEdge( Gedge edge ){
              firstEdge = edge;
         }//end of setFirstOutEdge
         public void incOutDegree(){
              outDegree++;
         }//end of incOutDegree
    }///:~
    //////////////end of node class /////////////
    ////////////// graph class ////////////////////
    //: AMGraph.java
    /************************* Revision History *************************
    *     v1.0 - Initial version:
    public class AMGraph implements IAMGraph {
         //2D-Array of graph nodes
         protected Gnode firstNode, node;
         //graph edges
         protected Gedge firstEdge, edge;
         private int gSize;
         /////////////// Constructor ///////////////
         public AMGraph(){
              firstNode = null;
              firstEdge = null;
              gSize = 0;
         /////////////// Accessors ///////////////
         public boolean isEmpty() {
              if ( firstNode == null){
                   return true;
              return false;
         }//end of isEmpty
         public boolean hasNeighbour() {
              // TODO Auto-generated method stub
              return false;
         }//end of hasNeighbour
         public int outDegree() {
              // TODO Auto-generated method stub
              return 0;
         }//end of outDegree
         public int inDegree() {
              // TODO Auto-generated method stub
              return 0;
         }//end of inDegree
         public void findPath(Object outBound, Object inBound) {
              // TODO Auto-generated method stub
         }//end of findPath
         public void printStationList(){
              Gnode temp = node;
              while( temp != null ){
                   System.out.println( temp.getID()+" "+temp.getStationName() );
                   temp = temp.getNextNode();
         }//end of printStationList
         public void printEdgeList( Gnode source ){
              Gedge temp;
              temp = source.getNextEdge();
              while( temp != null ){
                   System.out.println( temp.getStationID()+" out "+temp.getOutBound()+" in "+temp.getInBound() );
                   temp = source.getNextEdge();
         }//end of printEdgeList
         * @return
         public int getOutDegree ( ){
              int degree = 0;
              while( node != null ){
                   degree = node.getOutDegree();
                   node = node.getNextNode();
              return degree;
         }//end of getOutDegree
         * @param data
         * @return
         public Gnode getGNode ( String data ){
              Gnode temp = node;
              while( temp != null ){
                   if( temp.getID().equals(data) ){
                        return temp;
                   else{
                        temp = temp.getNextNode();
              return null;
         }//end of getGnode
         public boolean containsEdge( Gnode node0, Gnode node1) {
    Gnode source = node0, dest = node1;
    Gedge tempEdge = source.getNextEdge();
    while ( tempEdge != null){
         if ( tempEdge.getOutBound().equals( dest.getID() ) ){
              System.out.println("true");
              return true;
         else{
              tempEdge = tempEdge.getNextEdge();
    System.out.println("false");
    return false;
         }//end of containsEdge
         /////////////// Transformers ///////////////
         public void addNode( Comparable data, Object stationName, Object stationID ) {
              node = new Gnode( data, stationName, stationID );
              if ( firstNode == null ){
                   firstNode = node;
              else{
                   node.setNextNode( firstNode );
                   firstNode = node;
    gSize++;
         }//end of addNode
         public void addEdge( Gnode source, Gnode oBound, Gnode iBound, Object outBound, Object inBound, Object stationID, Object lineName ) {
    Gnode s = source;
    Gnode o = oBound;
    Gnode i = iBound;
    edge = new Gedge( s, o, i, outBound, inBound, stationID, lineName);
         s.setNextEdge( edge );
         edge.setNextEdge( s.getNextEdge() );
         }//end of addEdge
         public void removeNode(Comparable data) {
              // TODO Auto-generated method stub
         }//end of removeNode
         public void removeEdge(Comparable data) {
              // TODO Auto-generated method stub
         }//end of removeEdge
    //////////////////////// end of graph class ////////////////////
    ///////////////////driver////////////////////////
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.StringTokenizer;
    * This class reads a text description of a metro subway system
    * and generates a graph representation of the metro.
    *<p>
    * The grammar for the file is described below in BNF. A typical line
    * in the file looks like this :
    * <code> 20 NorthStation Green 19 22 Orange 15 22 </code>
    * where :
    * 20 is the StationID
    * NorthStation is the StationName
    * Green 19 22
    * Green is the LineName
    * 19 is the StationID of the outbound station
    * 22 is the StationID of the inbound station
    * Orange 15 22 is a LineID in which :
    * Orange is the LineName
    * 15 is the StationID of the outbound station
    * 22 is the StationID of the inbound station
    * Therefore, NorthStation has two outgoing lines.
    * note : 0 denotes the end of a line : i.e. in this case,
    * OakGrove would be at the end of the line, as there is no other outbound
    * station.
    *<p>
    * metro-map ::= station-spec* <BR>
    * station-spec ::= station-id station-name station-line+ <BR>
    * station-id ::= (positive integer) <BR>
    * station-name ::= string <BR>
    * station-line ::= line-name station-id station-id <BR>
         public class MetroMapParser {
              private BufferedReader fileInput;
              static AMGraph graph = new AMGraph();
              LinkedList l = new LinkedList();
              public static void main(String[] args){
                   if(args.length != 1){
                        usage();
                        System.exit(0);
                   String filename = args[0];
                   try{
                        MetroMapParser mmp = new MetroMapParser(filename);
                        mmp.generateGraphFromFile();
                   catch(Exception e){
                        e.printStackTrace();
              private static void usage(){
                   //prints a usage message to System.out
                   System.out.println("java ex3.MetroMapParser <filename>");
              * @effects: creates a new parser that will read from the file
              * filename unless the file does not exist. The filename should specify
              * the exact location of the file. This means it should be something like
              * /mit/$USER/6.170/ex3/bostonmetro.txt
              * @throws java.io.IOException if there <tt>filename</tt> cannot be read
              * @returns a new MetroMapParser that will parse the file filename
              public MetroMapParser(String filename) throws IOException{
                   //     a buffered reader reads line by line, returning null when file is done
                   fileInput = new BufferedReader(new FileReader(filename));
              * @effects: parses the file, and generates a graph from it, unless there
              * is a problem reading the file, or there is a problem with the format of the
              * file.
              * @throws java.io.IOException if there is a problem reading the file
              * @throws ex3.BadFileException if there is a problem with the format of the file
              * @returns the Graph generated by the file
              public void generateGraphFromFile()
                   throws IOException, BadFileException{
                   String line = fileInput.readLine();
                   StringTokenizer st;
                   String stationID;
                   String stationName;
                   String lineName = null;
                   String outboundID = null, inboundID = null;
                   while(line != null){
                        st = new StringTokenizer(line);
                        //          We want to handle empty lines effectively, we just ignore them!
                        if(!st.hasMoreTokens()){
                             line = fileInput.readLine();
                             continue;
                        //from the grammar, we know that the Station ID is the first token on the line
                        stationID = st.nextToken();
                        if(!st.hasMoreTokens()){
                             throw new BadFileException("no station name");
                        //     from the grammar, we know that the Station Name is the second token on the line.
                        stationName = st.nextToken();
                        graph.addNode( stationName, stationName, stationID );
                        if(!st.hasMoreTokens()){
                             throw new BadFileException("station is on no lines");
                        while(st.hasMoreTokens()){
                             lineName = st.nextToken();
                             if(!st.hasMoreTokens()){
                                  throw new BadFileException("poorly formatted line info");
                             outboundID = st.nextToken();
                             if(!st.hasMoreTokens()){
                                  throw new BadFileException("poorly formatted adjacent stations");
                             inboundID = st.nextToken();
                             //working like this although print edgelist appears to be going into infinite loop
                             graph.addEdge( graph.getGNode( stationID ) , graph.getGNode( outboundID ), graph.getGNode( inboundID ), outboundID, inboundID, stationID, lineName );
                        line = fileInput.readLine();
    //////////////////end of driver//////////////////
    /////////////// this is the info I'm testing put in a txt file//////////
    1 M               Blue 5 3 Red 2 5
    2 N               Blue 4 1
    3 O               Blue 1 5 Red 0 4
    4 P               Blue 5 2 Red 3 5
    5 Q               Blue 1 4 Red 3 2
    ////////////////end of txt file///////////////////

    that didn't come out to well - try again
    Help Having a problem with my directed graph, and its been frying my head. from the test that I've ran ita ppears to be working sort of the problem that I'm having is once I've created a node, I then attach an edge to that node, however where there are multiple edges it will only attach the last edge that it comes to. I'm creating a list of nodes, then trying to attach a list of edges to that particular node. code listing - theres a lot, sorry
    //////////////////// graph class ///////////////
    //: AMGraph.java
    /************************* Revision History *************************
    *     v1.0 - Initial version:
    public class AMGraph implements IAMGraph {
         //2D-Array of graph nodes
         protected Gnode firstNode, node;
         //graph edges
         protected Gedge firstEdge, edge;
         private int gSize;
         /////////////// Constructor ///////////////
         public AMGraph(){
              firstNode = null;
              firstEdge = null;
              gSize = 0;
         /////////////// Accessors ///////////////
         public boolean isEmpty() {
              if ( firstNode == null){
                   return true;
              return false;
         }//end of isEmpty
         public boolean hasNeighbour() {
              // TODO Auto-generated method stub
              return false;
         }//end of hasNeighbour
         public int outDegree() {
              // TODO Auto-generated method stub
              return 0;
         }//end of outDegree
         public int inDegree() {
              // TODO Auto-generated method stub
              return 0;
         }//end of inDegree
         public void findPath(Object outBound, Object inBound) {
              // TODO Auto-generated method stub
         }//end of findPath
         public void printStationList(){
              Gnode temp = node;
              while( temp != null ){
                   System.out.println( temp.getID()+" "+temp.getStationName() );
                   temp = temp.getNextNode();
         }//end of printStationList
         public void printEdgeList( Gnode source ){
              Gedge temp;
              temp = source.getNextEdge();
              while( temp != null ){
                   System.out.println( temp.getStationID()+" out "+temp.getOutBound()+" in "+temp.getInBound() );
                   temp = source.getNextEdge();
         }//end of printEdgeList
         * @return
         public int getOutDegree ( ){
              int degree = 0;
              while( node != null ){
                   degree = node.getOutDegree();
                   node = node.getNextNode();
              return degree;
         }//end of getOutDegree
         * @param data
         * @return
         public Gnode getGNode ( String data ){
              Gnode temp = node;
              while( temp != null ){
                   if( temp.getID().equals(data) ){
                        return temp;
                   else{
                        temp = temp.getNextNode();
              return null;
         }//end of getGnode
         public boolean containsEdge( Gnode node0, Gnode node1) {
    Gnode source = node0, dest = node1;
    Gedge tempEdge = source.getNextEdge();
    while ( tempEdge != null){
         if ( tempEdge.getOutBound().equals( dest.getID() ) ){
              System.out.println("true");
              return true;
         else{
              tempEdge = tempEdge.getNextEdge();
    System.out.println("false");
    return false;
         }//end of containsEdge
         /////////////// Transformers ///////////////
         public void addNode( Comparable data, Object stationName, Object stationID ) {
              node = new Gnode( data, stationName, stationID );
              if ( firstNode == null ){
                   firstNode = node;
              else{
                   node.setNextNode( firstNode );
                   firstNode = node;
    gSize++;
         }//end of addNode
         public void addEdge( Gnode source, Gnode oBound, Gnode iBound, Object outBound, Object inBound, Object stationID, Object lineName ) {
    Gnode s = source;
    Gnode o = oBound;
    Gnode i = iBound;
    edge = new Gedge( s, o, i, outBound, inBound, stationID, lineName);
    /*works sort of*/
         s.setNextEdge( edge );
         edge.setNextEdge( s.getNextEdge() );
    /*finish working here sort of*/
         }//end of addEdge
         public void removeNode(Comparable data) {
              // TODO Auto-generated method stub
         }//end of removeNode
         public void removeEdge(Comparable data) {
              // TODO Auto-generated method stub
         }//end of removeEdge
    ////////////// end of graph class////////////////

  • Do you know a VI to detect numerical zeros in a graph?

    I need to detect numerical zeros in a graph and I don't know the analytical formula of the function represented on the graph.

    If you just want to detect zeros in the array that represents the graph just search the array for zeroes...However if you want to detect zero crossings you can do it as described here:
    http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RPAGEID=135&HOID=5065000000080000008B2B0000&UCATEGORY_0=_49_%24_6_&UCATEGORY_S=0&USEARCHCONTEXT_QUESTION_0=Zero+crossing&USEARCHCONTEXT_QUESTION_S=0
    A similar example can be found on:
    http://sine.ni.com/apps/we/niepd_web_display.DISPLAY_EPD4?p_guid=B123AE0CB8F6111EE034080020E74861&p_node=DZ52028&p_submitted=N&p_rank=&p_answer=&p_source=External
    Or if it fits you task; use the in-build zero crossing point by point detector that comes with LabVIEW...
    If you do it by detecting changes in sign you can interpolate
    between the two points to find the exact position of the crossing. Attached is an example that does just that.
    MTO
    Attachments:
    zerocrossing_Interpolated.llb ‏22 KB

  • Directed graph problem

    I need to represent a transport network in java and have found that a graph seems to be the best way to do this, I initially thought that an undirected graph would be best but after thinking about it I need a directed graph in order to represent weightings for routes in each direction.
    Is there a type of graph or java class I should use for this purpose?

    You could look at:
    http://sourceforge.net/projects/jgrapht/
    Pete

  • 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

  • Longest path from node 0, in a acyclic directed graph(DAG)

    I'm having some problems finding the longest path from node 0 to any other node, as long as it is the longest path from node 0.
    I have done topological sorting from node 0.
    I have also made another algorithm which returns a 2-D matrix of relative distance between the nodes.
    For example:
    A DAG of order 10 has the following adjacency list and matrix:
    10(order)
    0 0 0 0 0 0 0 0 1 0
    1 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 0
    0 0 0 0 0 1 0 0 0 0
    1 0 0 0 0 0 0 1 1 1
    1 1 0 0 1 0 0 1 0 0
    0 1 1 1 0 0 0 0 0 0
    1 0 1 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0 0 1
    0 0 0 0 0 0 0 0 0 0
    10 (order)
    8
    0
    5
    0 7 8 9
    0 1 4 7
    1 2 3
    0 2
    9
    The distance matrix values for the above graph are:
    00 10 10 10 10 10 10 10 01 02
    01 00 10 10 10 10 10 10 02 03
    10 10 00 10 10 10 10 10 10 10
    02 02 03 00 02 01 10 02 03 03
    01 10 02 10 00 10 10 01 01 01
    01 01 02 10 01 00 10 01 02 02
    02 01 01 01 03 02 00 03 03 04
    01 10 01 10 10 10 10 00 02 03
    10 10 10 10 10 10 10 10 00 01
    10 10 10 10 10 10 10 10 10 00
    The distance matrix above shows the shortest path between nodes, unfortunatley I need to find the longest path.
    Can someone please help me with the algorithm for that, I have been awake for a long time and I still can't figure it out.....

    So you just want someone to write your entire script as soon as possible (today), so you can hand it in for homework? Seems sensible to me.

  • Change Node Shape in Javascript Infovis Toolit/ Force Directed Graph

    Hi All,
    I am using Javascript Infovis toolkit(JIT) and want to change the shape of a node to some image.. How can I do that? The default shape is circle and it can be changed further to rectangle, square, ellipse etc but in my case, I need to change it into an image present at my local disc drive.
    They say its possible to do so in the 'type' field but what all methods do we need to add or see the impact on...?? See the below link:
    http://thejit.org/static/v20/Docs/files/Options/Options-Node-js.html
    And how exactly can we do it?
    Help please...

    Yea I guess so bcoz Infovis Toolkit is the API of Javascript i.e. JIT (Javascript Infovis Toolkit)

  • Removing Cycles from Graphs

    Hello,
    is anyone familiar with the problem of removing cycles from a directed graph G? I would like to form a DAG G' where all possible paths that are present in G are still present in G', except that these paths don't have to be infinite (the cycles can be traversed only once).
    Thanks
    sergey

    there are many algorithms
    one of the best is dijkstra s algorithm
    you will find more in graph theory books
    you can also create sink trees
    sink trees are the trees which do not have cycles in them
    dijkstra s algorithm is also used to create sink trees so maybe ur problem will also be solved
    i dont have much info about it
    but i read it in a book by tenenbaum
    i think it was called computer networks
    if u have the book check the network layer chapter

  • Problem in faces-config.xml cycle detection

    Hi,
    I'm having the following problem in my jsf application. I have a loginMangager bean which holds a reference to the logged user and which is used by many other beans in my application. But in a particular situation I'm getting the following error:
    SEVERE: JSF will be unable to create managed bean listaChecagemBean when it is requested.  The following problems where found:
         - Managed bean mesaTarefasBean contains cyclic references.  Evaluation path: mesaTarefasBean -> loginManager -> listaChecagemBean -> loginManager.My faces-config.xml looks like this:
      <managed-bean>
        <managed-bean-name>loginManager</managed-bean-name>
        <managed-bean-class>
          br.gov.pgfn.efdv.mesa.view.login.LoginManagerBean
        </managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
      <managed-bean>
        <managed-bean-name>listaChecagemBean</managed-bean-name>
        <managed-bean-class>
          br.gov.pgfn.efdv.mesa.view.ListaChecagemBean
        </managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
          <property-name>loginManager</property-name>
          <value>#{loginManager}</value>
        </managed-property>
        <managed-property>
          <property-name>mesaTarefasBean</property-name>
          <value>#{mesaTarefasBean}</value>
        </managed-property>
        <managed-property>
          <property-name>listaChecagemFacade</property-name>
          <value>#{listaChecagemFacade}</value>
        </managed-property>
      </managed-bean>
      <managed-bean>
        <managed-bean-name>mesaTarefasBean</managed-bean-name>
        <managed-bean-class>br.gov.pgfn.efdv.mesa.view.MesaTarefasBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
        <managed-property>
          <property-name>loginManager</property-name>
          <value>#{loginManager}</value>
        </managed-property>
        <managed-property>
          <property-name>mesaTarefasFacade</property-name>
          <value>#{mesaTarefasFacade}</value>
        </managed-property>
      </managed-bean>As you can see, there is not really a cycle here since the loginManagerBean does not depend on any other bean. If you think of it as directed graph, listaChecagemBean is connected to mesaTarefasBean and both of them are connected to the loginManagerBean, which is not connected to any other bean, it's a sink node.
    I'm a missing something? Is this a bug?
    I'm using JSF 1.2 RI 1.2_05 and Tomcat 6.0.
    Thanks in advance,
    Andr� Rodrigues

    Hi Ryan,
    I still problems with the release 1.2_07 which works fine with 1.2_04 when I use external beans through a custom el-resolver.
    <?xml version="1.0" encoding="UTF-8"?>
    <faces-config xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
         version="1.2">
         <application>
              <el-resolver>net.t_mobile.test.resolver.TestELResolver</el-resolver>
         </application>
         <managed-bean>
              <managed-bean-name>sessionBean</managed-bean-name>
              <managed-bean-class>net.t_mobile.test.beans.SessionBean</managed-bean-class>
              <managed-bean-scope>session</managed-bean-scope>
              <managed-property>
                   <property-name>externalBean</property-name>
                   <value>#{externalBean}</value>
              </managed-property>
         </managed-bean>
         <managed-bean>
              <managed-bean-name>dummyA</managed-bean-name>
              <managed-bean-class>net.t_mobile.test.beans.DummyBean</managed-bean-class>
              <managed-bean-scope>session</managed-bean-scope>
              <managed-property>
                   <property-name>sessionBean</property-name>
                   <value>#{sessionBean}</value>
              </managed-property>
         </managed-bean>
         <managed-bean>
              <managed-bean-name>dummyB</managed-bean-name>
              <managed-bean-class>net.t_mobile.test.beans.DummyBean</managed-bean-class>
              <managed-bean-scope>session</managed-bean-scope>
              <managed-property>
                   <property-name>sessionBean</property-name>
                   <value>#{sessionBean}</value>
              </managed-property>
              <managed-property>
                   <property-name>parentBean</property-name>
                   <value>#{dummyA}</value>
              </managed-property>
         </managed-bean>
    </faces-config>
    The dependencies are like follows:
    dummyB.parentBean = dummyA
    dummyB.sessionBean = sessionBean
    dummyA.sessionBean = sessionBean
    sessionBean.externalBean = externalBean (resolved through external el-resolver)
    If I remove "dummyB" or the reference to externalBean no cycles are detected anymore.
    Could you confirm this bug?
    Regards,
    Marc

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

Maybe you are looking for

  • Crystal Report Source is MS SQL Stored Procedure Causes Login Popup

    My environment is this:  Visual Studio 2010 with CRforVS_13_0_9 installed.  MS SQL Server is source for all report data.  I use three different databases for all my reports. I have a number of working CR reports that work fine in IDE and at runtime. 

  • My SQL Developer is not working correctly! help

    hello!! My problem here is not like I can't live or work but it is REALLY annoying, see my SQL Developer is not taking any key different from letters and the space bar, I mean, if I use the enter key, doesn't change the line, if i use the backspace k

  • Developer 6.0 Form

    How can I check which item in a tlist is selected? I used to check whether the tlist control is null to determine if any thing selected, but it does not work when depolying the same form in web. It seems that oracle cannot detect any list changed eve

  • Failed AD privileges

    Hi Experts, Presently I am working on SAP IDM 7.2 SP9. Need your help to fix one issue. In my current project there are so many users whose AD privileges status is failed due to CN/DN issue while their account already exist in AD. Is there any way to

  • Disk Utility: Disk Scrubbing ("Erase Free Space")

    Hi, I've logged in case 113969827 the following observation: In a Macbook 10.5.6 using Disk Utility to Erase Free Space (Disk Utility / Erase / Erase Free Space) with 7-Pass or 35-Pass Erase on a / partition with 113GB free of 200GB of a 232GB drive