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

Similar Messages

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

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

  • 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

  • Saving waveform to retrieve it back to display on waveform graph

    I want to save a waveform that I acquire through my hardware and display it on a sweep chart. Its a time based voltage acquisition. I tried using write to spread sheet or save waveform options in LabVIEW 2009. But when I tried to read it, it only shows me 1 cycle of data(I will be suing a graph here because I want to add cursors to it). I want the exact same whole waveform to be displayed on a graph as I had acquired it. I want to avoid using express vi's since I will be acquiring 10 channels simultaneously so I dont want to slow down the execution speed.
    I am attaching the base vi that i made to read and write the waveform to a file(I am using simulate signal in this attached vi just to simulate a square wave and check my logic functionality).
    Can anyone help, please!
    Thanks in advance.
    Attachments:
    ro_up_read.vi ‏17 KB
    ro_up_write.vi ‏53 KB

    First of all, the "Append" should only be True when i does not equal 0.
    Secondly, you are only dealing with 1 signal, so have the dynamic data converter output a 1D array of scalers.  I then found that I had to transpose the spreadsheet on both sides (read and write).
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Write and Read Simulated Signal.png ‏86 KB

  • Draw by mouse the edges of an XY graph to calculate the perimeter and the area of it

    I have signals taken from a stabilometer ... I have plot X in terms of y in an XY graph and I want to know how I can plot by mouse a cricle that join most of the points which is the graph of X in terms of Y and calculate the area of it plus the perimeter. I have attached my labview program with two file X and Y 
    Solved!
    Go to Solution.
    Attachments:
    xB.txt ‏341 KB
    yB.txt ‏305 KB
    read data.vi ‏344 KB

    Try this. I create a circle, center where you click on the XY plot. Change the radius accordingly.
    CLD Certified 2014
    Attachments:
    read data.vi ‏157 KB

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

  • Dual graph algorithm

    Hello to all of you!
    Does anyone know a known algorithm to create the dual graph of a planar (undirected) graph? Or could you give me a hint? I tried to devise a DFS approach, which would use the back and cross edges of the DFS tree in order to form the faces. The problem is that I need the set of disjoint minimum cycles. Thus I would need an algorithm to calculate the difference AUB - A^B, for two cycles A,B, where B is a part of A. By the way, is there any recommended representation of a face?
    Thank you in advance and thaks for your time!
    P.S. For those who would ask what is a face, a face is the area defined by a minimum cycle e.g.:
    In this mesh (ignore dots):
    a-b-c
    I . I . I
    d-e-f
    a,b,c,d form a face
    b,c,e,f form a face
    and there is also the external face -which by the way how can it be defined?
    P.S.2 the Dual Graph is the graph formed by representing each face as a node and each edge which separates two faces, as an edge between the two newlly created nodes.

    OK , guess you're right! Since the following graph:
    O     O
    |\   /|
    | \ / |
    |  O  |
    | / \ |
    |/   \|
    O     O
    and this one
    O---
    |    \
    | O  |
    | | \|
    | |  O
    | | /|
    | O  |
    |   /
    O---are the same, however they have a different embedding AND dual graph.
    So, the embedding is defined by the coordinates of the nodes, along with
    their connectivity info.
    This means that for a start I need an algorithm to return the different faces of
    the graph. (at least these ones have to be fixed in number -no?). Then from
    the topological information for each face I should check their neighboring
    relations.
    For the face discovery I have thought of the following algorithm (in language):
    Create the DFS tree
    -Start from the root r of the DFS tree and visit each neighboring node based
    on the preordering number
    -When we reach a node b which has one or more back-edges we have a
    cycle.
    --For each back edge we go back to the node bs, starting from the
    back-edge which leads us to the node bs with the greatest start time
    (gretest preorder number).
    --from this node, bs, visit neighboring nodes, again based on preordering,
    until we find the node b (which will complete the cycle)
    ---While going towards b follow in reverse direction, each backedge that
    terminates a currntly visited node, and starts from a node t whose
    preorder[t] <= preorder[b]  (to avoid bypassing b by going deeper in the tree)
    and
    postorder[t] > postorder[b] (to avoid reaching another branch)
    -When we reach a node, cs,which has a cross edge to another node, ce, of
    the DFS tree (as a cross edge I mean a (u,v) where pre[u]>pre[v] and
    post[u]>post[v]) we have found another cycle, thus a face
    --from ce we go up the DFS, i.e., in reverse preordering, until we find a node
    a whose postorder[a] > post[cs]
    --from a we go down the DFS (in preordering) choosing the neighbor, an,
    whose postorder[an] >= postorder[cs] (equality means we have found cs
    thus we're done).  While descending we follow the same rules as before, in
    the case of the back edge.Of course the implementation of this algorithms has to support two-way movement in the DFS tree. The distinction between tree,back and cross edges is made through the pre and post ordering.
    I'm not sure but i think that, with the restrictions I have put, this algorithm can be ran while discovering and creating the DFS tree, rather after the DFS tree has been fully created.
    So if the algorithm IS correct, I only need a way to derive the connectivity between the produced faces via their topological information. That is, apart from the indisputable fact that if two faces have two nodes in common, they are neighbors, we have to locate all other edges between faces.
    One idea is for each pair of faces to check their min and max, X and Y coordinates. I have a sense that for faces f1and f2 where,
    f1_max_X > f2_max_X and
    f1_min_X < f2_min_X and
    f1_max_Y > f2_max_Y and
    f1_min_Y < f2_min_Y
    (there must be at most one equality (i.e. <=)but I guess its no harm to add all equalities there)
    holds, f1 and f2 are neighbors, thus an edge (f1,f2) must exist in the dual graph.
    Of course I have written a lot but I really would like to know if there's a "good" algortihm to create faces out there and a technique to create edges between faces given the coordinates.
    I propose the ideas in case someone finds something wrong and reports it or otherwise someone else finds my answer useful in the same topic.
    Thank you in advance!
    Message was edited by:
    M.M.

  • 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

  • Breadth-first traversal on a graph.. need help

    I need to make a graph, then run a breadth-first traversal on it. Do I simply make an undirected graph first, then implement the traversal?
    the graph should be like this:
    A - D - G
    B - E - H
    C - F - I
    Message was edited by:
    LuckY07
    Message was edited by:
    LuckY07
    null

    I just would like to print something to the screen showing it ran, such as the letters. What would be an easy way to do this using the DirectedGraph implementation? tks.
    here is my code:
    import ADTPackage.*;     //packages needed to make graph.
    import GraphPackage.*;
    public class graphTraversal
         public static void main(String[] args)
              GraphInterface<String> graph = new DirectedGraph<String>();     //creates graph.
              //adds vertices.
              graph.addVertex("A");
              graph.addVertex("B");
              graph.addVertex("C");
              graph.addVertex("D");
              graph.addVertex("E");
              graph.addVertex("F");
              graph.addVertex("G");
              graph.addVertex("H");
              graph.addVertex("I");
              //adds edges.
              graph.addEdge("A", "B");
              graph.addEdge("A", "D");
              graph.addEdge("A", "E");
              graph.addEdge("D", "G");
              graph.addEdge("D", "G");
              graph.addEdge("G", "H");
              graph.addEdge("H", "I");
              graph.addEdge("I", "F");
              graph.addEdge("F", "C");
              graph.addEdge("C", "B");
              graph.addEdge("B", "E");
              graph.addEdge("E", "H");
              graph.addEdge("E", "F");
              graph.addEdge("F", "H");
              System.out.println("total number of vertices: " + graph.getNumberOfVertices());
              System.out.println("total number of edges: " + graph.getNumberOfEdges());
              graph.getBreadthFirstTraversal("A");
         }     //end main.
    }

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

  • Problem: mapping mouse co-ordinates to a list of nodes in a graph.

    Hi.
    I have an undirected graph containing many nodes, some represent squares/tiles and some represent rooms in a board-game called Cluedo.
    Each node has an ID: -
    Rooms are called by the room name. -> Kitchen/Lounge
    Squares are called by the concatenated x/y position. -> A1/A2/K20
    I have created an algorithm to find the shortest path between two nodes in the graph.
    The problem I'm faced with is finding a way to map co-ordinates on the image file to these IDs. I have seen an implementation of a similar idea with an invisible image acting as a "colour-mask", so when the click hits the graphical map a function works out the colour of that pixel on the "colour-mask" and then uses a look-up table to find out which ID that is associated to.
    The problem with the above is that a Cluedo board has about 22x22 tiles and several rooms (each room would occupy several tiles in an undefined shape.)
    I've provided two example map files:
    http://www.dcs.qmul.ac.uk/~ade1/map.gif
    http://www.dcs.qmul.ac.uk/~ade1/map2.gif
    Does anyone have a suggestion of how I could solve this problem using what's available to me with Java?
    I'd appreciate any suggestions,
    Alexander Ellis

    Create a two-dimensional array that maps from grid coordinates to node/room objects.
    NodeOrRoom[][] grid = new NodeOrRoom[22][22];
    grid[0][0] = kitchen;
    grid[1][0] = kitchen;
    nodeLookup(int pixelTop, int pixelLeft) {
      return grid[pixelTop / gridCellHeight][pixelLeft / gridCellWidth];
    }Matthew

  • Array to graph

    Hi, in my VI, I already have one XY Graph to display some results but I retrieve all the Y values from it so as to make changes to one of them and now I am going to feed this batch of new y values back into a new XY Graph and plot a new curve. But now the problem seems to be that the 2 curves that I have are not similar when they should be similar except for the point that I changed the value. So can anyone please tell me what must I do to achieve what I want.
    Thanks.  
    Attachments:
    Parse_Graylevel.vi ‏123 KB
    polar2.vi ‏29 KB
    Step 1.zip ‏37 KB

    From the data I got from my first XY Graph, would it be possible to ask the computer to check if which points are out of range from the curve? Retrieve these points add or subtract 180 to or from them and add them back into the original data and form another new curve.
    Attachments:
    Parse_Graylevel (Better Version).vi ‏103 KB
    polar2.vi ‏29 KB
    Step 1.zip ‏37 KB

  • Graph Theory question...

    My graph knowledge is still requiring maturing. ;) I was wondering if anyone could help me with this question:
    given a set of verticies in an undirected graph, (not all may be connected) I want to determine whether there exists a "walk" from Vi to Vj and if so, I want to work out the shortest "path" between the two.
    I can use a matrix to define my graph view no problems, but how to determine all this computationally is a bit challenging.
    Richie !

    shortest path, as in the "Traveling Sales Person" problem does not require all possible paths to be searched, but it does require setup as if all would be searched (British Museaum style of search using a depth first algorithm). Heuristic clipping of paths can be done once you have an inital path of length L. Any time you reach L length you need not follow that path, nor any of its children. If you reach the destination in shorter than L length, then take the new path as the optimal path length and continue until all paths are exhausted.

  • Maximum weighted matching in graphs

    hi,
    does anyone know a maximum weighted matching algorithm for non bipartite undirected graphs? I want to implement it using java.if u knw pl reply
    bye!

    Hi throbi!
    You can view the source code of the 5th applet: http://www.math.sfu.ca/~goddyn/Courseware/
    The algorithm is mainly in the following file:
    http://www.math.sfu.ca/~goddyn/Courseware/matching/non_bipartite_perfect_matching/Algorithm.java
    You can remove some unnecessary methods, which are just for visualization, the result is less then 1000 lines.
    br,
    zgabi

Maybe you are looking for

  • Maintenance Item assignment to a Maintenance Plan

    Dear Expert, we need some help about the following scenario. Currently we are working on preventive maintenance in SAP ECC 6.0 system. We have created several maintenance items without assignment to maintenance plans in order to use them like models:

  • Cursor not focusing in the text field after Object tag load in IE

    Hi, We have an applets class "ABC.class" in our application. To include this class in a jsp page we are using OBJECT tag. This tag is written inside a if block in the jsp page. Based on the if condition this OBJECT tag has to be loaded. Below is the

  • Naming the database in palm

    hi , iam writing some data into a recordstore in palm using J2mE in netbeans. the data is stored in some J9RMS_11490944069700.PDB on the handheld which when synched comes into the backup diectory inside palm . Is there any way by which icn rename the

  • Why does BackgroundMediaPlayer NOT play mp3 streams?

    I tried to make a universal app, I have a successful Win8 app, now I have tried to make a WinPhone version and find that this class can't play mp3 streams, for example http://europaplus.hostingradio.ru:8014/europaplus256.mp3

  • Officially Unlocking iPhone 4?

    Hello, My brother gave me an iPhone 4 which he directly purchased from an Apple Store in the US and for which he paid full price.  It was never activated or used in US.  It is being used in Bahrain with Batelco, a seemingly authorized carrier.  I wan