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

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.

  • Searching bridge in undirected graph

    Hi,
    we have a homework to school to find a bridge in undirected graph.
    We got input:
    8 - number of nodes
    0 3 - node 0 is connected with node 3
    1 3
    2 3
    4 5
    4 6
    4 7
    3 4
    0 1
    1 2
    5 6
    6 7
    0 0 - end of input
    Here is a correct output for this graph:
    3 4 - edge from node 3 to node 4 is a bridge
    0 0 - end of output
    Here is my code which work perfectly for any graphs i think about but when i tried to commit it to our evaluating system it fails in 5 cases from 10. System says that it fails on diamond graph without needlepoint. I think I must have something wrong when i go throught graph (some condition or something). I tried to implement algorithm described here [http://www.cs.ucr.edu/~neal/2005/cs141/wiki/index.cgi?Cs141_Home/Lecture10] So if you know whats wrong or you have some idea please help.:)
    package pal;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    class Node{
    enum NodeState {
    White, Gray, Black
    NodeState state = NodeState.White;
    int id = 0;
    int hm = 0;
    int zm = 0;
    int from = -1;
    boolean root = false;
    ArrayList<Node> children = new ArrayList<Node>();
    public int min(int hm, int zm){
    int min;
    if(hm < zm){
    min = hm;
    return min;}
    else{
    min = zm;
    return min;
    public void tree(){
    if(state == NodeState.White){
    state = NodeState.Gray;
    for (int i = 0; i < children.size(); i ){
    if (children.get(i).state == NodeState.Black){ continue;}
    else if (children.get(i).state == NodeState.Gray && children.get(i).id == from){continue;}
    else if(children.get(i).state == NodeState.Gray && children.get(i).id != from){
    zm = min(children.get(i).hm,zm);
    continue;
    else{
    children.get(i).from = id;
    children.get(i).hm = hm  +1;+
    +children.get(i).zm = children.get(i).hm;+
    +children.get(i).tree();}+
    +}+
    +if(state != NodeState.Black && root){+
    +state = NodeState.Black;+
    +}+
    +else if(!root && state != NodeState.Black){+
    +state = NodeState.Black;+
    +for (int i = 0; i< children.size();i ++){
    if(children.get(i).id == from){
    children.get(i).zm = min(children.get(i).zm, zm);
    children.get(i).tree();
    public class Main {
    public static void main(String[] args) throws IOException {
    Node n;
    int node1, node2;
    int non;
    ArrayList<Node> nodeList = new ArrayList<Node>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    non = Integer.parseInt(br.readLine());
    for(int i = 0; i < non; i++){
    n = new Node();
    n.id = i;
    if(i==0){
    n.root = true;
    nodeList.add(n);
    while(true){
    StringTokenizer st = new StringTokenizer(br.readLine());
    node1 = Integer.parseInt(st.nextToken());
    node2 = Integer.parseInt(st.nextToken());
    if( (node1+node2) == 0) break;
    nodeList.get(node1).children.add(nodeList.get(node2));
    nodeList.get(node2).children.add(nodeList.get(node1));
    /*for(int i = 0; i < non ; i++){*
    *nodeList.get(i).tree();*
    nodeList.get(0).tree();
    // System.out.println("--------------");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < non; i++){
    if((nodeList.get(i).zm == nodeList.get(i).hm)&& !nodeList.get(i).root){
    sb.append(nodeList.get(i).from);
    sb.append(" ");
    sb.append(nodeList.get(i).id);
    sb.append("\n");
    sb.append("0 0");
    System.out.println(sb);

    xtem wrote:
    Hi,
    we have a homework to school to find a bridge in undirected graph.
    We got input:
    8 - number of nodes
    0 3 - node 0 is connected with node 3
    1 3
    2 3
    4 5
    4 6
    4 7
    3 4
    0 1
    1 2
    5 6
    6 7
    0 0 - end of input
    Here is a correct output for this graph:
    3 4 - edge from node 3 to node 4 is a bridge
    0 0 - end of output
    Here is my code which work perfectly for any graphs i think about but when i tried to commit it to our evaluating system it fails in 5 cases from 10. System says that it fails on diamond graph without needlepoint. I think I must have something wrong when i go throught graph (some condition or something). I tried to implement algorithm described here [http://www.cabletrain.com] So if you know whats wrong or you have some idea please help.:)
    package pal;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    class Node{
    enum NodeState {
    White, Gray, Black
    NodeState state = NodeState.White;
    int id = 0;
    int hm = 0;
    int zm = 0;
    int from = -1;
    boolean root = false;
    ArrayList<Node> children = new ArrayList<Node>();
    public int min(int hm, int zm){
    int min;
    if(hm < zm){
    min = hm;
    return min;}
    else{
    min = zm;
    return min;
    public void tree(){
    if(state == NodeState.White){
    state = NodeState.Gray;
    for (int i = 0; i < children.size(); i ){
    if (children.get(i).state == NodeState.Black){ continue;}
    else if (children.get(i).state == NodeState.Gray && children.get(i).id == from){continue;}
    else if(children.get(i).state == NodeState.Gray && children.get(i).id != from){
    zm = min(children.get(i).hm,zm);
    continue;
    else{
    children.get(i).from = id;
    children.get(i).hm = hm  +1;+
    +children.get(i).zm = children.get(i).hm;+
    +children.get(i).tree();}+
    +}+
    +if(state != NodeState.Black && root){+
    +state = NodeState.Black;+
    +}+
    +else if(!root && state != NodeState.Black){+
    +state = NodeState.Black;+
    +for (int i = 0; i< children.size();i ++){
    if(children.get(i).id == from){
    children.get(i).zm = min(children.get(i).zm, zm);
    children.get(i).tree();
    public class Main {
    public static void main(String[] args) throws IOException {
    Node n;
    int node1, node2;
    int non;
    ArrayList<Node> nodeList = new ArrayList<Node>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    non = Integer.parseInt(br.readLine());
    for(int i = 0; i < non; i++){
    n = new Node();
    n.id = i;
    if(i==0){
    n.root = true;
    nodeList.add(n);
    while(true){
    StringTokenizer st = new StringTokenizer(br.readLine());
    node1 = Integer.parseInt(st.nextToken());
    node2 = Integer.parseInt(st.nextToken());
    if( (node1+node2) == 0) break;
    nodeList.get(node1).children.add(nodeList.get(node2));
    nodeList.get(node2).children.add(nodeList.get(node1));
    /*for(int i = 0; i < non ; i++){*
    *nodeList.get(i).tree();*
    nodeList.get(0).tree();
    // System.out.println("--------------");
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < non; i++){
    if((nodeList.get(i).zm == nodeList.get(i).hm)&& !nodeList.get(i).root){
    sb.append(nodeList.get(i).from);
    sb.append(" ");
    sb.append(nodeList.get(i).id);
    sb.append("\n");
    sb.append("0 0");
    System.out.println(sb);

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

  • Suggestions about interface: graph, directed and undirected graph

    Hello all,
    I'm having some doubts about the right 'choice' of interfaces. I'm designing a little library for graphs and I was thinking about the difference between directed and undirected graphs, and how I should reflect this in the library. My apologies for my bad English.
    There is a small, but elegant, difference between directed and undirected graphs. Therefor, I don't know if it's worth to distuingish this difference in interfaces or not. I'll explain the difference by example. Usually, you can ask a directed graph the following queries:
    - all out-edges of a node + the total of such edges (outdegree)
    - all in-edges of a node + indegree
    - the successors of a node
    - the predecessors of a node
    The same questions can be asked to a undirected graph, but the in-edges and the out-edges of a node are equal, the successors and the predecessors are equal, etc... Thats basically the only difference between directed and undirected graphs.
    I found some solutions to define graphs, directed graphs and undirected graphs by means of interfaces.
    [1] one interface, duplicate methods, no tagging interfaces
    public interface Graph {
        Set getOutEdges(Node node);
        int getOutDegree(Node node);
        Set getinEdges(Node node);
        int getinDegree(Node node);
        Set getSuccessors(Node node);
        Set getPredecessor(Node node);
        boolean isDirected(); // no tagging interface
    }[2] one interface, duplicate methods, tagging interfaces
    public interface Graph {
        Set getOutEdges(Node node);
        int getOutDegree(Node node);
        Set getinEdges(Node node);
        int getinDegree(Node node);
        Set getSuccessors(Node node);
        Set getPredecessor(Node node);
    public DirectedGraph extends Graph { } // tagging interface
    public UndirectedGraph extends Graph { } // tagging interface[3] three interfaces
    public interface Graph {
    public interface DirectedGraph extends Graph {
        Set getOutEdges(Node node);
        int getOutDegree(Node node);
        Set getinEdges(Node node);
        int getinDegree(Node node);
        Set getSuccessors(Node node);
        Set getPredecessor(Node node);
    public interface UndirectedGraph extends Graph {
        Set getTouchingEdges(Node node);
        int getdegree(Node node);
        Set getNeighbors(Node node);
    }In the first solution, you dont know at compile time whether a graph is directed or undirected. However, it is very elegant for algorithms, since a lot of algorithms work for directed and undirected graphs. The main disadvantage of this solution is that you have duplicate functions in case of of undirected graphs: getOutEdges and getInEdges return the same set, etc.
    The difference between the first and the second solution is that the second solutions gives a way to detect whether a graph is directed or undirected at compile-time.
    The third solution has two seperate interfaces. This is much logical, and you know the graphtype at compile-time. However, this approach might lead to bloated code, as the algoritms for undirected and directed graphs now have two graphtypes (this can ofcourse be fixed by itroducing some kind of decorator, which in fact simulates the first solution).
    As I don't have much experience in design, I can't forsee any big problems or disadvantes of one of the approaches. Therefor, I would like to ask for your opinion. What approach is most common and best practice?
    Thanks in advance.

    I would tend to go with true inheritance for this case. There is a strong ISA relationship between a graph and uni-directional and bi-directional graphs. Programming to an interface (as in the Lyskov substitution principle) will give you a parallel heirachy of interfaces and implementations. This can become a problem if you start out not knowing what interface needs to be published, but in the case of graphs this should not be a problem. With a heirachy all the shared code can be written once. In this case the specialized code will just simplify calling more general code in the parent class.
    If all your graphs fit into memory then the implemenation should not be a problem. I used to work with map data where the graph does not fit into memory. Then you have to be careful about your interface or you will be getting calls that cannot be properly optimized "behind the scenes". Another specialization is in game programming where nodes are not actually expanded until they are "arrived at". Then you have to keep information about what parts of the structure are fleshed out and which are provisional.

  • 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

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

  • Unable to find oracle.dss.thin.beans.graph.ThinGraph package.

    Hi,
    How do i find this package. I am using JDEVELOPER 1.3 and i am able to generate graphs using the xml model method. What i want is to be able to generate the graph directly using a SQL without an XML.
    I want to use BI graph and generate graphs. SQL will be provided by me at runtime in the JSP and data returned by sql will be used by graph for plotting. How do i do this?
    http://oraclebi.blogspot.com/2005/11/using-bi-beans-with-non-olap-data.html
    i am using the above link as reference but was unable to locate or install the package where do i find it and how do i proceed..
    Please help
    Arjun Surendra

    Make sure that you have moved Oracle BI Graph to the right hand "selected Libraries" side.
    Also when you are under Profiles -> Development -> Libraries -> Oracle BI Graph. select Oracle BI graph & click on edit.
    under classpath you should see the associated jar files.
    Eg: C:\JDeveloper\jlib\bigraphbean.jar;C:\JDeveloper\jlib\bigraphbean-nls.zip
    Good luck!
    Kavitha

  • ACO for finding best paths on a graph.

    hello,
    i am trying to use aco alg to print shortest path from a specified source node to a destination node. i have created a graph where i have all the vertices (array of strings) and edges(neighbours) stored. I am trying to get the ants to trail randomly on the connected edges from start to dest and then return the route.please can someone give me some advice??.
    my code is as follows,...
    public class ACOLevel7 {
         private static myGraph g = new myGraph();
         public static void main(String[] args) {
              String start = "";
              String finish = "";
         ACOLevel7 p = new ACOLevel7(g,start,finish);
    /* instance variables */
         protected String[] names = g.getNames();
         protected boolean[] Edges;
         private static String istart;
         private static String idestination;
         private static int iAntSteps = idestination.length();
    private static int iColonySize = 10000;
    private static double iPheromoneStrength = 1.8d;
    private static int iEvaporationSpan = 100;
    private static double iEvaporationRate = 0.98d;
    private boolean[][] graphEdges;
    private Random iRandom = new Random();
    /* constructor */
    public ACOLevel7(myGraph g, String start, String finish) {
         Map map = new Map();
         istart = start;
         idestination = finish;
         graphEdges = g.getEdges();
         if(g.validStartAndFinish(istart,idestination)){
         double bestScore = -1;
         System.out.println("Level 7");
         System.out.println(">>> Here is your route planner! <<<");
         for (int i = 0; i < iColonySize; i++) {
         Ant ant = new Ant();
         ant.wander(map, iAntSteps);
         double score = calcScore(ant.getTrail());
         ant.dropPheromones(score);
         if (score > bestScore) {
         System.out.println(String.format(" %5d %s %4.2f", (new Object[]
         { new Integer(i), ant.print(), new Double(score) })));
         bestScore = score;
         (map).tick();
         System.out.println("\n>>> finished <<<");
         else {
              System.out.println("\n>>> start or finish not in names array<<<");
    double calcScore(AntTrail trail) {
    double score = 0;
    for (int i = 1; i <= iAntSteps; i++);
    //      Gets the next Node to travel to
    I NEED HELP HERE!!
         String String = idestination.substring(i - 1);
    return (score / 55d) * iPheromoneStrength;
    private class Map {
    /* instance variables */
    HashMap Map = new HashMap();
    Location iStart = new Location();
    /* constructor */
    public Map() {
    Map.put(iStart.getKey(), iStart);
    public Location start() {
    return iStart;
    public ArrayList to(Location fromHere) {
    // generate every vertex location that is valid from here
    ArrayList newLocations = new ArrayList();
    for (int i = 0; i < istart.length(); i++) {
    Location n = new Location(fromHere,
    String.valueOf(istart.String(i)));
    if (!Map.containsKey(n.getKey()))
    Map.put(n.getKey(), n); // add to the map
    else
    n = (Location)Map.get(n.getKey()); // existing location
    newLocations.add(n);
    return newLocations;
    public void tick() {
    Iterator i = Map.entrySet().iterator();
    while (i.hasNext())
    if (((Location)((java.util.Map.Entry)i.next()).getValue())
    .evaporate())
    i.remove();
    private class Location {
    private String iKey;
    private String iname;
    private double iPheromones = 1;
    private int iEvaporation = iEvaporationSpan;
    /* constructor: start location */
    public Location() { istartt = ""; }
    /* constructor: from another location */
    public Location(Location from, String names) {
    iKey = from.getKey() + "|" + names;
    istartt = names;
    public String getKey() {
    return iKey;
    public String getName() {
    return istartt;
    //public String getidestt(){
    public void dropPheromones(double d) {
    iPheromones += d;
    iEvaporation = iEvaporationSpan; // reset the evaporation counter
    public double getPheromones() {
    return iPheromones;
    public boolean evaporate() {
    iPheromones = iPheromones * iEvaporationRate;
    return --iEvaporation == 0;
    private class Ant {
    private AntTrail iTrail = new AntTrail();
    public void wander(Map map, int steps) {
    iTrail.addStep(map.iname());
    for (int i = 0; i < steps; i++)
    step(map);
    private void step(Map map) {
    ArrayList choices =map.to(iTrail.current());
    Location next = null;
    double span;
    // sum the available span
    span = 0;
    Iterator i1 = choices.iterator();
    while (i1.hasNext())
    span = span + ((Location)i1.next()).getPheromones();
    // choose an index value
    double index = iRandom.nextDouble() * span;
    // find the location within the span with this index
    span = 0;
    Iterator i2 = choices.iterator();
    while (i2.hasNext()) {
    next = (Location)i2.next();
    span = span + next.getPheromones();
    if (index < span) break;
    // add the chosen location to the trail
    iTrail.addStep(next);
    public AntTrail getTrail() {
    return iTrail;
    public void dropPheromones(double score) {
    iTrail.dropPheromones(score);
    public String print() {
    return iTrail.print();
    private class AntTrail {
    private ArrayList iTrail = new ArrayList();
    public void addStep(Location n) {
    iTrail.add(n);
    public Location getStep(int index) {
    return (Location)iTrail.get(index);
    public Location current() {
    return getStep(iTrail.size() - 1);
    public void dropPheromones(double score) {
    Iterator i = iTrail.iterator();
    while (i.hasNext())
    ((Location)i.next()).dropPheromones(score);
    public String print() {
    String s1 = "";
    Iterator i = iTrail.iterator();
    while (i.hasNext()) {
    String s2 = ((Location)i.next()).getName();
    if (!s1.equals("") && !s2.equals("")) s1 += "-";
    s1 += s2;
    return s1;
    }

    Presumably the thing that you want to do is to choose a path from a small number of alternatives based on some continually changing probability distribution (based on your Phermone strength)
    Consider the simple case, where you choose between two paths, one with weight 17 and one with weight 5.
    You sum the two weights, T = 17+5 = 22
    You generate a random number between 1 and 22
    and if it is less than 17 you choose the first path and if it is greater you choose the other path. Given the uniform distribution of your random numbers you have choosen the first path 17/22nds of the time.
    In more general terms, without integer weights
    You have a collection of n weights, Wi, you total them, T
    You choose a random number, R, between zero and T (i.e. choose a random number between 0 and 1 and multiply by T) This effectively normalizes your distribution.
    Then you subtract W1 from R. If the result went below zero your value was less than W1 so you take path1, if not, subtract W2 from R (R has already been reduced by W1 so what you are testing is whether your original random number was between W1 and W2) if it goes below zero take path 2, ...
    Go through the weights in order until you get a result below zero.
    This is the classical algorithm to select an alternative from a small number of possible alternatives where each alternative has a known probability of being selected.
    I hope that helped. I did not actually read your code to see what you are doing, I just looked at the comment prior to the I NEED HELP HERE and made a guess as to what your problem was.
    In the future, you will be more likely to get help quickly if you summarize your problem rather than just posting a wad of unreadable code.
    So if I answered your question, your welcome, if not, well perhaps you can take a little more effort to explain your problem so that we don't have to work so hard to figure out what you want.
    I am assuming that you know about the Random class and actually know how to generate simple random numbers. You see, you really didn't tell us what your problem is and where you need help, and thus force us to make assumptions.

  • Finding all unique paths in graph

    can anyone suggest an algorithm to find all unique paths between two nodes?
    I have already implemented a variation of Dijkstra's shortest path algorithm to find ONE path, i'm just not sure how I can find ALL unique paths..
    Any help much appreciated.
    thanks :)

    I'm not really sure about the english terminology to be used and most of inteligent discussions ends up with finding the proper words for definitions :)
    Let me just say I wrote the algorhytm that found all 3 paths in the small example graph (I know, I know. Still testing. Besides I don't want to prove that the code is complete in mathemathical meaning). The limitations are like for every real life path finding algorhytms (let's go from a to b, 0 or more paths may exists, 2 nodes may have 0 or 1 connection, the connetions are not directed, i want unique paths, and I don't want circles in any of the paths).
    In the iteration
    - I check if the path is ends with ENDNODE
    - I get all the neighbors of the last node and generate all the possible paths extending the current (exceptions: path never can include the same node twice) and add them into a queue
    - I get the first from the queue and that is the current path now.
    The iteration ends when I have no more paths to analyze.
    If I undestood the term "unique path" as it can have any circles in it then I may agree with you, but thats another problem.
    In that case (if I had a school homework or I was working for a science group which has no access downloading these kind of algorhytms and they must come up with one for some reason :) I think I'd try to find all the unique circles first then all the paths (without the circles) and then combined them in all the way...
    I'll improve and test the algorhytm before publish it.

  • Ignoring back edges in an undirected graph...

    let's say i have a graph with 3 vertices. then let's say i have 2 edges connecting vertex 1 (v1) with vertex 2 (v2), and there's one edge connecting v2 with vertex 3 (v3). i want only to print edges going to each vertex, not 'back' edges. how do i do that?
    //given - Graph 'g'
    Iterator it = g.vertices();
    while(it.hasNext()){
    Vertex v = (Vertex)it.next();
    VertexElement a = v.element();
    System.out.println(vertexElement);
    Iterator fit = g.incidentEdges(v);
    while(fit.hasNext()){
    Edge e = (Edge)fit.next();
    EdgeElement = e.element();
    System.out.println(EdgeElement);
    this prints out every edge associated with each vertex.

    alright guys, sorry for the previous confusion... i guess i'll go ahead and show all the code associated so you can get a good idea on what i'm trying to do. we're making an airline reservation system built upon a graph in which the vertices are 'airports' and the edges are 'flights'
    the information is stored in a text file, which a certain format for airports and a slightly different format for flights. we read the text file, read in the airports and assign them as vertices, then read in the flights, and assign those to edges on the corresponding vertices (there are 'destination' and 'origin' values so we can keep track of which edge to place the elements) the format of the text file is described in detail in the class code, but i'll give an example at the bottom.
    here are the classes
    AIRPORT CLASS
    * Airport information in text file...
    * the information in the text file has 2 sections of data, each section is
    * separated by a bang (!) line:
    *                � Airport Information
    *                � Flight Information
    * the information is presented in padded fields of known length. ex. the first
    * 3 characters in the airport section is the unique airport abbreviation.
    * Fields:                                (variable associated)
    * #3 - Airport abbreviation           :  'airportID'
    * #1 <padding>                        :
    * #5 - Time Zone (offset from GMT)    :  'timeZone'
    * #1 <padding>                        :
    * #3 - X Coordinate on map            :  'xCoord'
    * #1 <padding>                        :
    * #3 - Y Coordinate on map            :  'yCoord'
    * #1 <padding>                        :
    * # remainder - Name of City/Airport  :  'airportCity'
    public class Airport {
      private int timeZone, xCoord, yCoord;
      private String airportID = "[UNASSIGNED]", airportCity = "[UNASSIGNED]";
    // blank constructor
      public Airport(){
      public Airport(String airportID, int timeZone, int xCoord, int yCoord,
                     String airportCity) {
        this.airportID = airportID;
        this.timeZone = timeZone;
        this.xCoord = xCoord;
        this.yCoord = yCoord;
        this.airportCity = airportCity;
      // accessor methods
      public String getID(){
          return airportID; }
      public int getTimeZone(){
          return timeZone; }
      public int getX(){
          return xCoord; }
      public int getY(){
          return yCoord; }
      public String getCity(){
        return airportCity; }
      // mutator methods
      public void setID(String airportID){
        this.airportID = airportID; }
      public void setTimeZone(int timeZone){
        this.timeZone = timeZone; }
      public void setXcoord(int xCoord){
        this.xCoord = xCoord; }
      public void setYcoord(int yCoord){
        this.yCoord = xCoord; }
      public void setCity(String airportCity){
        this.airportCity = airportCity; }
      // toString
      public String toString(){
        return ("AIRPORT ID: " + airportID + '\n' +
                "TIME ZONE: " + timeZone + '\n' +
                "X/Y: " + xCoord + "/" + yCoord + '\n' +
                "CITY: " + airportCity); }
    }FLIGHT CLASS
    package lab06;
    * Airline Flight Schedule - USA: Starts after the '!' delimiter.
    * Fields:                               (variable associated)
    * #2 - Airline                       :  'airline'
    * #4 - Flight                        :  'flightNum'
    * #2 <padding>                       :
    * #3 - Origin Airport                :  'originAirport'
    * #1 <padding>                       :
    * #5 - Departure Time                :  'departTime'
    * #2 <padding>                       :
    * #3 - Destination Airport           :  'destinationAirport'
    * #1 <padding>                       :
    * #5 - Arrival Time                  :  'arriveTime'
    * #2 <padding>                       :
    * #2 - Meals (S=snack/L=lunch/       :
    *             D=dinner/B=b-fast/     :
    *             #=depends on class)    :  'meals'
    * #4 <padding>                       :
    * #1 - # of stops during flight      :  'stops'
    * #4 <padding>                       :
    * #3 - Aircraft type                 :  'aircraftType'
    * #12 <padding>                      :
    * # remainder - Booking classes      :
    *               [IGNORE THIS DATA]   :
    public class Flight {
      private int flightNum, stops;
      private String
      airline = "[UNASSIGNED]", originAirport = "[UNASSIGNED]",
      departTime = "[UNASSIGNED]", destinationAirport = "[UNASSIGNED]",
      arriveTime = "[UNASSIGNED]", meals = "[UNASSIGNED]",
      aircraftType = "[UNASSIGNED]";
    // blank constructor
      public Flight(){
      public Flight(String airline, int flightNum, String originAirport,
                    String departTime, String destinationAirport, String arriveTime,
                    String meals, int stops, String aircraftType) {
        this.airline = airline;
        this.flightNum = flightNum;
        this.originAirport = originAirport;
        this.departTime = departTime;
        this.destinationAirport = destinationAirport;
        this.arriveTime = arriveTime;
        this.meals = meals;
        this.stops = stops;
        this.aircraftType = aircraftType;
      // accessor methods
      public String getAirline(){
          return airline; }
      public int getFlightNum(){
          return flightNum; }
      public String getOrigin(){
          return originAirport; }
      public String getDepartTime(){
          return departTime; }
      public String getDestination(){
        return destinationAirport; }
      public String getArriveTime(){
        return arriveTime; }
      public String getMeals(){
        return meals; }
      public int getStops(){
        return stops; }
      public String getAircraftType(){
        return aircraftType; }
      // mutator methods
      public void setAirline(String airline){
        this.airline = airline; }
      public void setFlightNum(int flightNum){
        this.flightNum = flightNum; }
      public void setOrigin(String origin){
        this.originAirport = origin; }
      public void setDepartTime(String departTime){
        this.departTime = departTime; }
      public void setDestination(String destination){
        this.destinationAirport = destination; }
      public void setArriveTime(String arriveTime){
        this.arriveTime = arriveTime; }
      public void setMeals(String meals){
        this.meals = meals; }
      public void setStops(int stops){
        this.stops = stops; }
      public void setAircraftType(String aircraftType){
        this.aircraftType = aircraftType; }
      // toString
      public String toString(){
          return ('\n' + "FLIGHT #" + airline + flightNum + '\n' +
                  "ORIGIN AIRPORT: " + originAirport + '\n' +
                  "DESTINATION: " + destinationAirport + '\n' +
                  "DEPARTS: " + departTime + " ARRIVES: " + arriveTime + '\n' +
                  "MEAL ON FLIGHT: " + meals + '\n' +
                  "NUMBER OF STOPS: " + stops + '\n' +
                  "AIRCRAFT TYPE: " + aircraftType); }
    }and here's my driver - it selects the text file (which must be formatted appropriately) and reads in each flight/airport and creates the graph.
    MAIN CLASS
    import java.io.*;
    import java.util.StringTokenizer;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import java.util.Iterator;
    import net.datastructures.*;
    import java.util.Vector;
    public class Driver extends JComponent{
      public static void main(String args[]){
        JPanel contentHolder;
        int status;
        StringTokenizer tokenizer;
        String first_, second_, third_, fourth_, fifth_, sixth_, seventh_,
        eighth_, ninth_, rest_, temp_, airportID, timeZone, xCoord, yCoord, airportCity;
        //create initially empty graph
        Graph g = new AdjacencyListGraph();
        //hash table to store information
        HashTable h = new HashTable();
        //display file chooser
        JFileChooser chooser = new JFileChooser();
        status = chooser.showOpenDialog(null);
        if(status != JFileChooser.APPROVE_OPTION)
          System.out.println("NO FILE CHOSEN.");
        else {
          //read file selected...
          try {
          File x = chooser.getSelectedFile();
          FileReader fr = new FileReader(x);
          BufferedReader inFile = new BufferedReader(fr);
          String info = "";
          String line = inFile.readLine();
          int numLines = 0; //keep track of # of lines in our file (if desired)
          boolean readingFlights = false;
          while(line != null){
            if (line.equals("!")) {  //we found the bang line, and now start reading
                                     //flight objects.
                line = inFile.readLine();
                readingFlights = true; }
            tokenizer = new StringTokenizer(line);
            int numTokens = tokenizer.countTokens();
            if (readingFlights) {
                first_ = tokenizer.nextToken();   //airline
                second_ = tokenizer.nextToken();  //flightNum
                third_ = tokenizer.nextToken();   //originAirport
                fourth_ = tokenizer.nextToken();  //departTime
                fifth_ = tokenizer.nextToken();   //destinationAirport
                sixth_ = tokenizer.nextToken();   //arriveTime
                //'meals' is a special case, since not all flights even have a meal
                //designated in the text file. those flights w/out meals can throw
                //our tokenizer off track, so we use a substring methods from here.
                seventh_ = line.substring(30,35); //meals
                eighth_ = line.substring(36,37);  //stops
                ninth_ = line.substring(41,44);   //aircraftType
                rest_ = line.substring(56,69);    //read rest of line
              //a test to see if the substrings are lined up right...
              //System.out.println("1st " + first_ + '\n' + "2nd " + second_ + '\n'
              //                 + "3rd " + third_ + '\n' + "4th " + fourth_ + '\n'
              //                 + "5th " + fifth_ + '\n' + "6th " + sixth_ + '\n'
              //                 + "7th " + seventh_ + '\n' + "8th " + eighth_ +
              //                 '\n' + "9th " + ninth_ + '\n' + "rest: " + rest_);
                //create flight object from this information
                //if(seventh_ == ""){
                Flight f1 = new Flight(first_, (Integer).parseInt(second_), third_,
                                       fourth_, fifth_, sixth_, seventh_,
                                       (Integer).parseInt(eighth_), ninth_);
                Vertex v1 = (Vertex)h.get(f1.getOrigin());
                Vertex v2 = (Vertex)h.get(f1.getDestination());
                Edge e1 = g.insertEdge(v1, v2, f1);
        } else {
            first_ = tokenizer.nextToken();       //airportID
            second_ = tokenizer.nextToken();      //timeZone
            third_ = tokenizer.nextToken();       //xCoord
            fourth_ = tokenizer.nextToken();      //yCoord
            fifth_ = tokenizer.nextToken("");     //airportCity (reads rest of line)
            //create airport object from this information
            Airport a1 = new Airport(first_, (Integer).parseInt(second_), (Integer).
                                     parseInt(third_), (Integer).parseInt(fourth_),
                                     fifth_);
            Vertex v1 = g.insertVertex(a1);
            h.put(a1.getID(), v1);
        } //close else
            line = inFile.readLine();
            numLines++; } //stop reading file
           //show info on screen
            Iterator it = g.vertices();
              while(it.hasNext()){
              Vertex v = (Vertex)it.next();
              Airport a = (Airport)v.element();
              System.out.println(a.getID());
            Iterator fit = g.incidentEdges(v);
              while(fit.hasNext()){
              Edge e = (Edge)fit.next();
              Flight curFlight = (Flight)e.element();
              //if the origin of the current flight is the same as the current
              //airport's ID then we wanna list those because those are the outgoing
              //flights from the current airport
              //System.out.println(curFlight.getOrigin().compareTo(a.getID()));
              System.out.println(curFlight);
              System.out.println("--------------------------------------" + '\n');
        catch(FileNotFoundException exception)
        { System.out.println("The file " + chooser.getSelectedFile() +
                             " was not found."); }
        catch(IOException exception)
        { System.out.println(exception); }
    }an example text file would look like this...
    ABQ -0800 195 275 Albuquerque, New Mexico
    DEN -0800 215 205 Denver, Colorado
    DTW -0600 445 140 Detroit, Michigan
    UA 785  ABQ  645A  DEN  757A  S     0    733            F  Y  B  M  Q
    CO 195  DEN  251P  ABQ  410P        0    73S            F  A  Y  Q  H
    AA 305  DTW  105P  ABQ  446P  #     1    72S            F  Y  H  B  Mthe first three lines are airports, separated by the bang line, then the next three lines are airports...
    the way the flights are set up, i want to display only outgoing flights...
    for example, under the Alberquerque airport display, the output will show flight UA785 leaving Alberquerque and arriving at Denver, BUT it will also show flights CO195 & AA305 coming INTO Alberquerque from Denver and Detroit, respectively. I don't want to see that. I only want to see the flights LEAVING a given airport.
    -Chris

  • Answer:  JgraphT-how to set a weight on an edge of undirected graph

    I'm sorry. that was stupid. if any of you use it you probably know I should use
    this definition:
    ListenableUndirectedWeightedGraph g = new ListenableUndirectedWeightedGraph ( );
    bye.

    Why didn't you answer this on the thread you started with the question, instead of letting people waste thier time answering it?

  • 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

  • Graph Problem - Finding Cliques

    Hi Folks,
    I'm stuck with a problem involving undirected graphs and was wondering if anyone might be able to help.
    I have a Vector containing pairs of letters which represent edges in a graph from one point to another. e.g. 'ab' would be an edge from point 'a' to point 'b'. In many cases this Vector contains a number of sub-graphs e.g.
    ab
    ac
    bc
    de
    df
    ef
    {ab, ac, bc} make up one complete sub-graph and {de, df, ef} makes up another, where each point has an edge to all the other points in the group.
    I want to be able to identify these sub-graphs and seperate them (or at least identify them as being different groups). In graph theory I believe these groups are known as cliques.
    I am only interested in finding maximal cliques (complete sub-groups) and in my particular situation a point will never exist in more than one clique (so no overlapping groups). Also the vector will only ever contain complete sub-graphs (no incomplete sub-graphs where edges are missing).
    Does anyone know how to solve this problem? Any help would be greatly appreciated. Please let me know if you need any more info.
    Regards,
    Jamie

    I use the following O(n^4 or less) method in my map-folding algorithm:
        static int fastGroups(Group[] group, boolean[][] join, int n) {
            int[] g = new int[n];
            boolean[] row;
            int c = 0, d;
            for(int i=0, j, k, m; i<n; i++) {
                for(j=i+1; j<n; j++) {
                    if(!join[ i][j]) continue;
                    for(m=0; m<c; m++) {
                       if(group[m].contains(i) && group[m].contains(j)) break;
                    if(m<c) continue;
                    for(k=0, d=0; k<n; k++) {
                        row = join[k];
                        if(!row[ i] || !row[j]) continue;
                        for(m=0; m<d; m++) if(!row[g[m]]) break;
                        if(m==d) g[d++] = k;
                    group[c++] = new Group(g,d);
            group[c] = null;
            return c;
        }This populates the cliques in the given array and returns the number of cliques.
    This method works with "well behaved" groups, where each group can be achieved by choosing some two elements of it and then searching the rest in order of appearance. So if you have the followin cliques (1,4,5), (2,5,6), (3,4,6) and (4,5,6):
    1-4-3
    5-6
    2
    you will miss the clique (4,5,6). In your case this should not be a problem.

  • 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

Maybe you are looking for

  • How to identify the file type in a safe way

    I need to identify the filetype of a file in my disc. I watched over internet and i've found this good site: http://filext.com/ that supplys the "magic bytes" for many kind of files. I have also looked over internet for some ready class that identify

  • Is it possible to have listener for orcale shut won event ?

    Hi, We know that during normal shut down of the oracle database, message is sent to the clients. Is it possible to have listener for that event using JDC ? Any suggestion is welcome. TIA, Sudarson

  • Disappearing PDF's

    I have a number of books stored in iPhoto, most of which contain pages of text in PDF.  When I open the books, wherever I have placed the PDF pages...they are gone.  The photo pages are still there, it's just the PDFs.  THose pages in the book are bl

  • Problems booting a PowerBook G4 15"

    Computer was being used on a hospital website to fill out applications (employment) and froze, remaining stuck in Safari with the rainbow disk spinning in place of the cursor. Was unable to force quit, forced computer to shut down instead and left. N

  • IDOC Status Messages Documentation

    Can anyone help me in sharing the link to see complete documsntation of various IDOC Statues. Thanks in advance.