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

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.

  • 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

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

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

  • 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

  • Reg - Search Form for a VO with group by clause

    Hi,
    I have a Bar graph that displays data based on the Query below.
    SELECT STATUS.STATUS_ID AS STATUSID,STATUS.STATUS,COUNT(SR.SERVICEREQUEST_ID) AS SRCOUNT
    FROM SERVICE_REQUEST SR ,SERVICEREQUESTSTATUS STATUS
    WHERE SR.STATUS_ID = STATUS.STATUS_ID
    GROUP BY STATUS.STATUS_ID,STATUS.STATUS,SR.STATUS_ID
    It displays the count of SRs against a particular status.
    Now I need to add a search form to this graph with customer and date range.
    So we need to add the line below to the where clause.
    "SR.CUSTOMER_ID = :customerId AND SR.REQUESTED_ON BETWEEN :fromDate and :toDate"
    But the columns SR.CUSTOMER_ID, SR.REQUESTED_ON also need to be added to the select clause to create the View criteria for search panel.
    The two columns should also need to be added to the group by clause if we are to add them in the select clause.
    This would not produce the expected results.
    How do I create a search form with the criterias applied only at the where clause.Please help.
    With Regards,
    Guna

    The [url http://docs.oracle.com/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/server/ViewObjectImpl.html]ViewObjectImpl has methods for doing this programmatically (setQuery, defineNamedWhereClauseParam, setNamedWhereClauseParam) that you can use to manipulate the query, the bind variables expected, and the values for the binds.
    John

  • Plotting xyz Coordinate​s on 3D Graph Help

    Hi,
    I have an array (max size 10) of xyz coordinates which i want to plot on a 3D graph.
    These 10 points are constantly moving (data from a Leap Motion hand tracker)
    I have attached a screen shot of simple VI and example data
    How would i go about gaphing this?

    Hi coqwas,
    That's a pretty interesting project you have there.
    I guess there is 2 types of 3D graph which you can find (use quick drop if you have to): 3D Line Graph and Active X 3D Curve Graph. You can find some examples on 3D graphs in NI Example Finder as well (Open LabVIEW >> Help >> Find Examples... >> Search key word "3D graph").
    Since it is a 3D array, can you tell me the array size for X, Y and Z (e.g. X size by Y size by Z size)? What does the row and column represents in the XYZ array shown inyour screenshot? 
    To use the 3D Line Graph.vi, you'll need to provide a 1D array of X vector, Y vector and Z vector. So you need to extract the values from that XYZ 3D array to those vectors respectively. You can extract the Z layers using Array Subset and Reshape array. Since I'm not really sure which part of the array (X, Y or Z) represents the finger no., you'll need to separate each array by individual fingers. Each XYZ array for each finger is fed to each create_plot_line.vi (4 fingers meaning 4 create_plot_line.vi) just as shown below:
    You can see there is a number from 0-3 at the create_plot_line.vi. Those are the plot ID (0 means plot 0 and 1 means plot 1). What I am trying to do above is that I'm ploting 4 plots in 1 3D graph. 
    The plot ID is specified by going to the front panel >> Right click on the 3D Line Graph >> select 3D Graph Properties >> go to Plots tab >> on the left column called Plots, add as many plots you want to plot into the 3D graph. 
    Additional info:
    http://zone.ni.com/reference/en-XX/help/371361H-01​/lvhowto/plotting_3d_graphs/
    http://www.ni.com/white-paper/9388/en/
    Warmest regards,
    Lennard.C
    Learning new things everyday...

  • 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

  • Open file search?

    Hi all,
    Im puzzled, if I do I search in a Mountain Lion finder window I get results like so:
    However, doing the same search via InDesigns FILE - OPEN pane, results in nothing?
    Am I missing something or is it a bug?
    Thanks
    Andy

    Yep I starting to think it's a bug.
    This is InDesign CS5 search:
    and this is InDesign CS6 search:
    Bridge is an option but I find it a pain to use.

  • Using Field Data for Interactive Graph?

    Hello,
    I work for a lighting company and our salesmen use in-house created sales materials on iPads in the field. We've found Acrobat PDF Files to be very effective in demonstrating how switching to different wattage bulbs can save them money, through the use of data calculation fields. However, we're also hoping to illustrate this visually through some type of interactive graph. Specifically, I'm trying to find a way, if possible, to make a "return on investment" bar graph that would tailor itself to the user. Here's an example of the type of graph I'm trying to make though a PDF:
    Basically, this chart shows how much of a initial investment (in this case ~$25,000) would be mitigated over 10 years (eventually saving the company over ~$70,000). Not that the details matter much... I just don't really know where to start. I have a small amount of experience using fields, and I'm versed enough for simple calcuation and pulling data from other fields, however I have no idea how to turn this data into a graph of this complexity (or even know if it's possible).
    Any advice would be vastly appeciated!
    Many thanks,
    Dan

    Your best best is to use some presentation software such PowerPoint or Keynote.
    On an iPad you could use Numbers to create the Graphs then put then copy the graphs into Keynote and have the run as interactive slides you click or touch an item like a slide.  I don't know of any software that create interactive Graphs That you can create graphs that grow or shrink by inputting numbers.
    I've Googled interactive Graph for Mac and come up with this:
    https://www.google.com/search?q=Intreractive+Graph+for+Mac&sourceid=mozilla-search&start=0 &start=0&ie=utf-8&oe=utf-8&client=mozilla
    and here is result for iPad:
    https://www.google.com/search?q=Intreractive+Graph+for+Mac&sourceid=mozilla-search&start=0 &start=0&ie=utf-8&oe=utf-8&client=mozilla#pq=intreractive+graph+for+mac&hl=en&gs_nf=1&tok= pFb9_G1GM62Cf32INLbniw&cp=27&gs_id=7oy&xhr=t&q=Intreractive+Graph+for+iPad&pf=p&client=moz illa&sclient=psy-ab&pbx=1&oq=Intreractive+Graph+for+iPad&aq=f&aqi=&aql=&gs_sm=&gs_upl=&bav =on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=43f3605c77841060&biw=1568&bih=755
    Note this not advertisment (spam) for any product on search results of things that can create interactive Graphs on Mac and iPads. 

  • Graph question

    hi, I have to do this project for a class, i dont want to know how to do it, just if someone can help point me in the right direction to get me started.
    Im supposed to take an undirected graph and construct an adjacency list representation of the graph.
    My question is,
    first, i am unclear on the deffinition of an undirected vs a directed graph.
    Second, what is the best way to construct this structure? Do I actraly create a graph object or use a linked list im just a little confused.
    Thanks for the help
    _stevebiks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    A undirected graph is one where the connections between nodes have no specific direction. They're not one-way streets, they're two-way streets.
    An adjacency list is a list of all node-pairs which are directly connected (they're neighbours in the graph). You can have a NodePair class to represent them. What actual data structure you use to hold them should be an implementation detail hidden in a class say AdjacencyList. You can start using an ArrayList but that shouldn't be known from the outside. The functionality of AdjacencyList depends on what you want to use it for but a minimum would be an add method and a way to iterate through all stored NodePair objects.

  • Transform a cluster in a graph

    I want to transform a cluster into a graph like in the example "peak detection".
    But i don't know what to do.
    Can you give me a methode to do that?

    There is a useful example in LV on this matter. Look at XY graph.vi in Search Examples / Fundamentals Examples / Graph Examples.
    Roberto
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

Maybe you are looking for

  • Custom Calculation Script almost works...

    I'm trying to creaet a form that uses a dropdown box to select the proper text for a text field.  I have created the form and the Custom Calculation for my Text box works great (Thanks to these forums!). The problem I am experincing now is that I wan

  • How to install 3c905c NIC in Solaris 8 in SPARC platform

    i bought a 3c905c NIC. I want to install it into SUN Blade 100 (SPARC platform) Solaris 8. I do need help how can I configure this NIC?tks.

  • Fault Management (FMA) visibilty to kernel memory

    Does FMA have visibility to kernel memory? I read some docs and it mentions about the cpumem-diagnosis module able to diagnose CPU & memory. It's not clear to me if it does kernel memory as well. Can someone clear that up for me? Thanks!

  • Guassian Blur hanging up in PS CS5.1 on 1 year old Mac Pro

    I am running Photoshop CS5.1 on a Mac Pro that is only about a year old (OS - Snow Leopard). The machine has 24GB of ram and I am devoting about 18GB of the ram to Photoshop. It doesn't matter how big the image is that I am working on but whenever I

  • Can't launch iTunes without Quicktime.

    I can't launch iTunes. It's telling me I need quicktime 7.5.5. I've uninstalled and reinstalled the latest versions of QT and iTunes and rebooted several times, and I'm still getting the same error message. It was fine 30 mins ago, now it's not worki