Shortest path issue

Hey guys, first...Happy thanksgiving :)
Ok, so I'm on my last assignment for my amazingly taught Data Structures class. I battled my way successfully through recursion, binary trees, redblack trees, 234 trees, B Trees, and heaps!...no issues at all!....but, now I have hit graphs. I understand the concept, but my latest assignment has me a bit frustrated..Im so close to finishing I can taste it!!....I just cant find the spoon..
Here we go:
We are given a graph on paper. It has circles (verteci) representing cities in the USA. These circles are connected by lines (edges) representing the distance between the cities. Also, the lines have arrows pointing the direction they may be traversed.
We are to construct the graph in the computer, and then compute the shortest path from washington (Vertex 0) to every other city.
I managed to construct the graph, and it will find the shortest path no problem. My only issue is that, it wants us to print the path it took, not just the destination and total distance....
I have tried using a stack to push the verteci onto as theyre visited, but im not getting happy results.
I should also mention, this code is taken out of the book with modifications by me so that it can add edges and verteci, and it now accepts String types for the vertex labels instead of characters.
Here is my code
PATH.JAVA (the important part)
// path.java
// demonstrates shortest path with weighted, directed graphs
// to run this program: C>java PathApp
import java.lang.*;
import java.io.*;
class DistPar               // distance and parent
{                           // items stored in sPath array
    public int distance;    // distance from start to this vertex
    public int parentVert;  // current parent of this vertex
    public DistPar(int pv, int d)  // constructor
        distance = d;
        parentVert = pv;
}  // end class DistPar
class Vertex
    public String label;        // label (e.g. 'A')
    public boolean isInTree;
    public Vertex(String lab)   // constructor
        label = lab;
        isInTree = false;
}  // end class Vertex
class Graph
    private final int MAX_VERTS = 20;
    private final int INFINITY = 1000000;
    private Vertex vertexList[];    // list of vertices
    private int adjMat[][];         // adjacency matrix
    private int nVerts;             // current number of vertices
    private int nTree;              // number of verts in tree
    private DistPar sPath[];        // array for shortest-path data
    private int currentVert;        // current vertex
    private int startToCurrent;     // distance to currentVert
    private stack path_taken;       // stack to record path taken
    public Graph()                  // constructor
        vertexList = new Vertex[MAX_VERTS];
                                         // adjacency matrix
        adjMat = new int[MAX_VERTS][MAX_VERTS];
        nVerts = 0;
        nTree  = 0;
        for(int j=0; j<MAX_VERTS; j++)      // set adjacency
            for(int k=0; k<MAX_VERTS; k++)  //     matrix
                adjMat[j][k] = INFINITY;    //     to infinity
        sPath = new DistPar[MAX_VERTS];     // shortest paths
        path_taken = new stack(MAX_VERTS);
    }  // end constructor
    public void addVertex(String lab)
        vertexList[nVerts++] = new Vertex(lab);
    public void addEdge(int start, int end, int weight)
        adjMat[start][end] = weight;  // (directed)
    public void path()                // find all shortest paths
        int startTree = 0;             // start at vertex 0
        vertexList[startTree].isInTree = true;
        nTree = 1;                     // put it in tree
      // transfer row of distances from adjMat to sPath
        for(int j=0; j<nVerts; j++)
            int tempDist = adjMat[startTree][j];
            sPath[j] = new DistPar(startTree, tempDist);
      // until all vertices are in the tree
        while(nTree < nVerts)
            int indexMin = getMin();    // get minimum from sPath
            int minDist = sPath[indexMin].distance;
            if(minDist == INFINITY)     // if all infinite
            {                        // or in tree,
                System.out.println("There are unreachable vertices");
                break;                   // sPath is complete
            else
            {                        // reset currentVert
                currentVert = indexMin;  // to closest vert
                startToCurrent = sPath[indexMin].distance;
                // minimum distance from startTree is
                // to currentVert, and is startToCurrent
            // put current vertex in tree
            vertexList[currentVert].isInTree = true;
            nTree++;
            path_taken.push(sPath[indexMin]);
            adjust_sPath();             // update sPath[] array
        }  // end while(nTree<nVerts)
        displayPaths();                // display sPath[] contents
        nTree = 0;                     // clear tree
        for(int j=0; j<nVerts; j++)
            vertexList[j].isInTree = false;
    }  // end path()
    public int getMin()               // get entry from sPath
    {                              //    with minimum distance
        int minDist = INFINITY;        // assume minimum
        int indexMin = 0;
        for(int j=1; j<nVerts; j++)    // for each vertex,
        {                           // if it's in tree and
            if( !vertexList[j].isInTree &&  // smaller than old one
                               sPath[j].distance < minDist )
                minDist = sPath[j].distance;
                indexMin = j;            // update minimum
        }  // end for
        return indexMin;               // return index of minimum
     }  // end getMin()
    public void adjust_sPath()
      // adjust values in shortest-path array sPath
        int column = 1;                // skip starting vertex
        while(column < nVerts)         // go across columns
         // if this column's vertex already in tree, skip it
            if( vertexList[column].isInTree )
                column++;
                continue;
         // calculate distance for one sPath entry
                       // get edge from currentVert to column
            int currentToFringe = adjMat[currentVert][column];
                       // add distance from start
            int startToFringe = startToCurrent + currentToFringe;
                       // get distance of current sPath entry
            int sPathDist = sPath[column].distance;
         // compare distance from start with sPath entry
            if(startToFringe < sPathDist)   // if shorter,
            {                            // update sPath
                sPath[column].parentVert = currentVert;
                sPath[column].distance = startToFringe;
            column++;
         }  // end while(column < nVerts)
    }  // end adjust_sPath()
    public void displayPaths()
        for(int j=0; j<nVerts; j++) // display contents of sPath[]
            System.out.print(vertexList[j].label + "="); // B=
            if(sPath[j].distance == INFINITY)
                System.out.print("inf");                  // inf
            else
                System.out.print(sPath[j].distance);      // 50
                String parent = vertexList[ sPath[j].parentVert ].label;
                System.out.print(" (" + parent + ") ");       // (A)
        System.out.println("");
        System.out.println("PRINTING path_taken");
        DistPar thing = null;
        while((thing = path_taken.pop()) != null)
            System.out.println(" " + vertexList[thing.parentVert].label + " "+ thing.distance);
}  // end class GraphSTACK.JAVA (my stack class)
// stack.java
// demonstrates stacks
// to run this program: C>java StackApp
class stack
    private int maxSize;        // size of stack array
    private DistPar[] stackArray;
    private int top;            // top of stack
    public stack(int s)         // constructor
        maxSize = s;             // set array size
        stackArray = new DistPar[maxSize];  // create array
        top = -1;                // no items yet
    public void push(DistPar j)    // put item on top of stack
        stackArray[++top] = j;     // increment top, insert item
    public DistPar pop()           // take item from top of stack
        return stackArray[top--];  // access item, decrement top
    public DistPar peek()          // peek at top of stack
        return stackArray[top];
    public boolean isEmpty()    // true if stack is empty
        return (top == -1);
    public boolean isFull()     // true if stack is full
        return (top == maxSize-1);
}PATHAPP.JAVA (test program..builds the graph and calls path())
class PathApp
    public static void main(String[] args)
        Graph theGraph = new Graph();
        theGraph.addVertex("Washington");
        theGraph.addVertex("Atlanta");
        theGraph.addVertex("Houston");
        theGraph.addVertex("Denver");
        theGraph.addVertex("Dallas");
        theGraph.addVertex("Chicago");
        theGraph.addVertex("Austin");
        theGraph.addEdge(0,1,600);
        theGraph.addEdge(1,0,600);
        theGraph.addEdge(0,4,1300);
        theGraph.addEdge(4,3,780);
        theGraph.addEdge(3,1,1400);
        theGraph.addEdge(1,2,800);
        theGraph.addEdge(2,1,800);
        theGraph.addEdge(4,5,900);
        theGraph.addEdge(4,6,200);
        theGraph.addEdge(6,4,200);
        theGraph.addEdge(6,2,160);
        theGraph.addEdge(3,5,1000);
        theGraph.addEdge(5,3,1000);
        System.out.println("Shortest Paths");
        theGraph.path();
        //theGraph.displayPaths();
        System.out.println();
}Im mostly having trouble comprehending the Path.java file. A few friends and I stared at it for a few hours and couldnt get it to do what we wanted...
path_taken is the stack I added in to try and push/pop the verteci as theyre traversed, but with what I stuck in right now, it still just prints the most recently visited vertex, and the sum of the distances.
Any help is greatly appreciated!
Thanks :)
----Arkhan

If your graph is G(V, E), and you're trying to get to vertex v_end, then create a new graph G'(V', E') whereV' = (V x N) U {v_end'}
    (v_end' is a new object)
E' = {((u, t), (v, t + f(u, v, t))) : (u, v) in E, t in N} U
     {((u, t), (u, t + 1)) : u in V, t in N} U
     {((v_end, t), v_end') : t in N}G' is infinite, so you'll need to use a lazy graph structure. Then just use Dijkstra from (v_start, 0) to v_end'.

Similar Messages

  • Network Model - Shortest Path

    Hi all,
    I have created spatial network containing non lrs sdo_geometry objects in Oracle 10g (Release 2). In this network model there are 33208 nodes and 42406 links.
    Now I need to write a java program to find shortest route between two selected nodes. Here is snippet of my source code.
    Connection connection = DriverManager.getConnection(dbUrl, databaseUser,   databasePassword);
    boolean readForUpdate = false;
    Network net= NetworkManager.readNetwork(connection, "SDO_ROAD_NETWORK", readForUpdate);
    Path path = NetworkManager.shortestPath(net, startNodeId ,endNodeId);
    System.out.println ("total distance " path.getCost() );+
    Link[] linkArray = path.getLinkArray();
    But this will throws an exception - Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    It was working fine for 1000 nodes and 1000 links. I tried by changing java options like -Xms and Xmx parameters but same result.
    Then I tried to find shortest route using pl/sql using following.
    DECLARE
    testNet VARCHAR2(30) := 'SDO_ROAD_NETWORK';
    startNode NUMBER := 120150;
    endNode NUMBER :=1740034;
    path NUMBER;
    linkArray SDO_NUMBER_ARRAY;
    BEGIN
    sdo_net_mem.network_manager.read_network('SDO_ROAD_NETWORK', 'FALSE');
    dbms_output.put_line('Loading finished');
    path := SDO_NET_MEM.NETWORK_MANAGER.SHORTEST_PATH_DIJKSTRA('SDO_ROAD_NETWORK', startNode, endNode);
    IF path IS NULL THEN
    dbms_output.put_line('route not found');
    return;
    END IF;
    linkArray := SDO_NET_MEM.PATH.GET_LINK_IDS(testNet, path);
    FOR i IN linkArray.first..linkArray.last
    LOOP
    dbms_output.put_line('Link -- ' || linkArray(i) || ' ' ||
    SDO_NET_MEM.LINK.GET_NAME (testNet, linkArray(i)) || ' ' ||
    SDO_NET_MEM.LINK.GET_COST (testNet, linkArray(i)));
    END LOOP;
    END;
    +/+
    But this takes nearly 4 minutes to just read the nework (sdo_net_mem.network_manager.read_network).
    Finally I dowloaded standalone java client application NDM Network Editor from OTN. This application loads entire network within 25 seconds and finds shortest route within 5 seconds.
    Please guide me how can I write improved code reading network. My requirement is to get shortest path between two nodes
    Thanks,
    Sujnan

    Hi Sujnan
    In the past there have been some performance issue for the Oracle JVM. Not sure if this addressed in the latest releases (10.r2 or 11).
    Performance Status OJVM used for SDO Network data Model 10R2.0.2
    Maybe the oracle guys can give an update.
    Luc

  • Shortest Path

    I have this table:
    with t as (
      select 'A' source, 'B' destination, 7 meter from dual
      union all
      select 'A' source, 'C' destination, 9 meter from dual
      union all
      select 'A' source, 'F' destination, 14 meter from dual
      union all
      select 'B' source, 'C' destination, 10 meter from dual
      union all
      select 'B' source, 'D' destination, 15 meter from dual
      union all
      select 'C' source, 'D' destination, 11 meter from dual
      union all
      select 'C' source, 'F' destination, 2 meter from dual
      union all
      select 'D' source, 'E' destination, 6 meter from dual
      union all
      select 'E' source, 'F' destination, 9 meter from dual
    select * from t;How to know the shortest path from a source to a destination? Suppose, from A to F. Can we show the shortest path using SQL? tx in advance.

    Billy  Verreynne  wrote:
    I dislike what I consider blatant non-SQL features in SQL. Basic XML functionality is not an issue for me. But XQuery and modelling clauses - that I dislike.I can understand that.
    Note that for the particular case we're discussing here, if I were to implement it in 11.2, I'd surely choose the recursive factoring approach instead.
    I agree, most of these XML features may appear powerful and "cool" but also "evil" (as you would say) if they're not understood and used correctly.
    BTW, for the record, the XQuery expression I posted is rewritten using SQL internal functions, so not much left of XML functionalities after all (except the name perhaps?).
    So, I guess that makes it appears less evil ;)
    SQL> explain plan for
      2  select source
      3       , destination
      4       , meter
      5       , xmlcast(
      6           xmlquery('sum(for $i in ora:tokenize($s,";") return xs:integer($i))'
      7            passing path as "s"
      8            returning content
      9           ) as number
    10         ) as "SUM"
    11  from (
    12    select level, t.*, sys_connect_by_path(meter, ';') path
    13    from paths t
    14    where destination = 'F'
    15    connect by prior destination = source
    16    start with source = 'A'
    17  )
    18  order by "SUM"
    19  ;
    Explained.
    SQL> set pages 100
    SQL> set lines 140
    SQL> select * from table(dbms_xplan.display(format => 'ALL'));
    PLAN_TABLE_OUTPUT
    Plan hash value: 2102804061
    | Id  | Operation                                  | Name                  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                           |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |   1 |  SORT AGGREGATE                            |                       |     1 |     2 |         |     |
    |   2 |   COLLECTION ITERATOR PICKLER FETCH        | XQSEQUENCEFROMXMLTYPE |  8168 | 16336 |    29   (0)| 00:00:01 |
    |   3 |  SORT ORDER BY                             |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |   4 |   VIEW                                     |                       |     9 | 18189 |     4  (25)| 00:00:01 |
    |*  5 |    FILTER                                  |                       |       |       |         |     |
    |*  6 |     CONNECT BY NO FILTERING WITH START-WITH|                       |       |       |         |     |
    |   7 |      TABLE ACCESS FULL                     | PATHS                 |     9 |   171 |     3   (0)| 00:00:01 |
    Query Block Name / Object Alias (identified by operation id):
       1 - SEL$33CAA0FD
       2 - SEL$33CAA0FD / KOKBF$@SEL$AEEEB114
       3 - SEL$1
       4 - SEL$2        / from$_subquery$_001@SEL$1
       5 - SEL$2
       7 - SEL$3        / T@SEL$3
    Predicate Information (identified by operation id):
       5 - filter("DESTINATION"='F')
       6 - access("SOURCE"=PRIOR "DESTINATION")
           filter("SOURCE"='A')
    Column Projection Information (identified by operation id):
       1 - (#keys=0) SUM(SYS_XQ_ATOMCNVCHK(TO_NUMBER(SYS_XQ_UPKXML2SQL(VALUE(KOKBF$),2,1,0)),2,33))[22]
       2 - VALUE(A0)[40]
       3 - (#keys=1) CAST(TO_CHAR( (SELECT SUM(SYS_XQ_ATOMCNVCHK(TO_NUMBER(SYS_XQ_UPKXML2SQL(VALUE(KOKBF$),2,1,0
           )),2,33)) FROM TABLE() "KOKBF$")) AS number        )[22], "SOURCE"[CHARACTER,1],
           "DESTINATION"[CHARACTER,1], "METER"[NUMBER,22]
       4 - "SOURCE"[CHARACTER,1], "DESTINATION"[CHARACTER,1], "METER"[NUMBER,22], "PATH"[VARCHAR2,4000]
       5 - SYS_CONNECT_BY_PATH(TO_CHAR("METER"),';')[4000]
       6 - "SOURCE"[CHARACTER,1], "DESTINATION"[CHARACTER,1], STRDEF[1], STRDEF[1], STRDEF[22], STRDEF[1],
           STRDEF[1], STRDEF[22], PRIOR NULL[1], LEVEL[4], SYS_CONNECT_BY_PATH(TO_CHAR("METER"),';')[4000]
       7 - "SOURCE"[CHARACTER,1], "T"."DESTINATION"[CHARACTER,1], "T"."METER"[NUMBER,22]
    Note
       - dynamic sampling used for this statement (level=2)
    49 rows selected.

  • Shortest path calculation in huge spatial network

    Looks like I have to load the whole network in order to perform shortest path calculation.
    such as NetworkManager.shortestPathAStar, NetworkManager.shortestPath
    Suppose the network is too big to be loaded at one time, what is the possible solution in Oracle spatial to solve this issue???

    I can’t think of a way of analysing the network in chunks as it would increase the complexity of the calculation and may miss routes. If you know the start and end point have you considered drawing a connecting line between the two, buffering it and just loading the network inside the area.
    You would need to check the route by increasing the buffer size and finding the shortest route again.
    Another option could be to divide the network into primary and secondary routes. Find the route from the start to the nearest primary node and from the end point to the nearest primary point then connect the primary nodes. Based in a quick Google this is sounds a bit like the algorithms Garmin and Tom Tom use.
    Message was edited by:
    grahamallan

  • Finding the shortest path router for the router tracking purpose

    Hi all,
    A Question asking you regarding to routers' tracking information.
    We keeps all the router infomation of our subnet in a file name "routers.txt" in this format:
    1 2 1
    2 4 1
    4 3 1
    1 3 5
    This states there are four routers, the distance between routers 1 and 2 is 1, between 2 and 4 is 1, etc.
    I need to write a Java program to keep track the shortest path between routers, I would understand that we can get this done easily in Java, but I am not a Java Savvy. I'm new in Java, would somebody help me to the right direction?
    In order to keep track the routers in our subnet easily,the output would look something like:
    Router 1
    To Router Distance Vector
    2 1 2
    3 3 2
    4 2 2
    Thanks very much,
    Cait.

    Hi kksenji,
    Well, because of the webform, it's not obvious to see. The output would be simple. From the input, for router 1 to router 2, the shortest distance is 1. For router 1 to router 3, the shortest distance is 3, for router 1 to router 4, the shortest distance is 2 and so on. The middle vector that it went through is 2 for every route. Hope this makes sense.
    Just try to solve the problem with the shortest distance, and I have a hard time to figure out the algorithm for this as well as how to get this started.
    Thanks, Cait.

  • Finding the shortest path

    Hey guys,
    Im working on a solution to this problem below is a program to allow a user to draw straight line paths. What i'd like to do is allow the user to select two points on the path he has drawn and find the shortest path among all the interesecting lines.....im going crazy thinking of a solution for this.....im thinking bout steeping down a notch and just try to find just any path first.
    Will really appreciate any help.
    Thnx in advance,
    Vikhyat
    import java.applet.*;*
    *import java.awt.*;
    import java.awt.event.*;*
    *import javax.swing.*;
    import java.awt.geom.*;
    public class Lab11 extends Applet implements MouseListener, MouseMotionListener {
    int x0, y0, x1, y1;
    int mouseRelease=0;
    GeneralPath path = new GeneralPath();
    public Lab11()
    addMouseListener(this);
    addMouseMotionListener(this);
    public void mouseDragged(MouseEvent e)
    x1 = e.getX();
    y1 = e.getY();
    repaint();
    public void mouseMoved(MouseEvent e) { }
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited (MouseEvent e) { }
    public void mousePressed(MouseEvent e) {
    x0 = e.getX();
    y0 = e.getY();
    System.out.println("Mouse pressed at: (" +
    x0 + ", " + y0 + ")" );
    public void mouseReleased(MouseEvent e) {
    x1 = e.getX();
    y1 = e.getY();
    System.out.println("Mouse released at: (" +
    x1 + ", " + y1 + ")" );
    mouseRelease = 1;
    this.repaint();
    public void paint(Graphics g)
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    //just for show not concerned with saving paths
    if(mouseRelease==1)
    path.moveTo(x0,y0);
    path.lineTo(x1,y1);
    mouseRelease = 0;
    g2.setPaint(Color.RED);
    g2.draw(path);
    g.setColor(Color.BLACK);
    g.drawLine(x0, y0, x1, y1);
    public static void main(String[] argv)
    JFrame f = new JFrame("Test");
    f.getContentPane().add(new Lab11());
    f.setSize(600,600);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }Pictorially this is what im trying to do:
    User draws a path like so and selects two points as shown in blue
    [http://i48.photobucket.com/albums/f236/theforrestgump/select.jpg]
    The program should then proceed to highlighting the shortest path
    [http://i48.photobucket.com/albums/f236/theforrestgump/sp.jpg]
    Edited by: cannonball on Apr 1, 2008 7:58 PM

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ShortPath extends JPanel {
        Path2D.Double path;
        Path2D.Double shortPath = new Path2D.Double();
        Point p1 = new Point();
        Point p2 = new Point();
        final double PROXIMITY = 5.0;
        public ShortPath() {
            path = new Path2D.Double();
            path.moveTo(145,80);
            path.lineTo(125,170);
            path.lineTo(190,200);
            path.lineTo(240,340);
            path.lineTo(285,220);
            path.lineTo(145,80);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            g2.draw(path);
            g2.setPaint(Color.green);
            g2.setStroke(new BasicStroke(2f));
            g2.draw(shortPath);
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(p1.x-2, p1.y-2, 4, 4));
            g2.setPaint(Color.orange);
            g2.fill(new Ellipse2D.Double(p2.x-2, p2.y-2, 4, 4));
        private void findShortPath() {
            if(!isPointOnLine(p1) || !isPointOnLine(p2)) {
                System.out.println("a point is not on the path");
                return;
            double d1 = getDistanceToPoint(p1);
            double d2 = getDistanceToPoint(p2);
            double pathLength = getDistanceToPoint(new Point());
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end   = new Point2D.Double();
            if((d1 < d2 && d2 - d1 < pathLength - d2 + d1) ||
               (d1 > d2 && d1 - d2 > pathLength - d1 + d2)) {
                start.setLocation(p1);
                end.setLocation(p2);
            } else {
                start.setLocation(p2);
                end.setLocation(p1);
            generatePath(start, end);
        //                        145,80
        // leg distance = 92.2    125,170
        // leg distance = 71.6    190,200   163.8
        // leg distance = 148.7   240,340   312.5
        // leg distance = 128.2   285,220   440.7
        // leg distance = 198.0   145,80    638.7
        private double getDistanceToPoint(Point p) {
            PathIterator pit = path.getPathIterator(null);
            double[] coords = new double[2];
            double distance = 0;
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                        start.setLocation(coords[0], coords[1]);
                        pit.next();
                        continue;
                    case PathIterator.SEG_LINETO:
                        end.setLocation(coords[0], coords[1]);
                line.setLine(start, end);
                boolean onLine = line.ptSegDist(p) < PROXIMITY;
                if(onLine) {  // point is on this line
                    distance += start.distance(p);
                    break;
                } else {
                    distance += start.distance(end);
                start.setLocation(end);
                pit.next();
            return distance;
        private void generatePath(Point2D.Double first, Point2D.Double second) {
            Point2D.Double p = new Point2D.Double(first.x, first.y);
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            boolean pathStarted = false;
            for(int j = 0; j < 2; j++) {
                PathIterator pit = path.getPathIterator(null);
                double[] coords = new double[2];
                while(!pit.isDone()) {
                    int type = pit.currentSegment(coords);
                    switch(type) {
                        case PathIterator.SEG_MOVETO:
                            start.setLocation(coords[0], coords[1]);
                            pit.next();
                            continue;
                        case PathIterator.SEG_LINETO:
                            end.setLocation(coords[0], coords[1]);
                            line.setLine(start, end);
                            boolean onLine = line.ptSegDist(p) < PROXIMITY;
                            if(onLine) {            // found point on line
                                Point2D.Double linePt = getClosestPoint(line, p);
                                Line2D.Double segment;
                                if(!pathStarted) {  // found first point
                                                    // both points on line
                                    if(line.ptSegDist(second) < PROXIMITY) {
                                        Point2D.Double secPt =
                                            getClosestPoint(line, second);
                                        segment = new Line2D.Double(linePt, secPt);
                                        shortPath.append(segment, false);
                                        return;
                                    } else {        // first point only
                                        segment = new Line2D.Double(linePt, end);
                                        shortPath.append(segment, false);
                                        p.setLocation(second);
                                        pathStarted = true;
                                } else {            // found second point
                                    segment = new Line2D.Double(start, linePt);
                                    shortPath.append(segment, false);
                                    return;
                            } else if(pathStarted) {
                                                    // add intermediate lines
                                Line2D.Double nextLine =
                                    new Line2D.Double(start, end);
                                shortPath.append(nextLine, false);
                    start.setLocation(end);
                    pit.next();
        private Point2D.Double getClosestPoint(Line2D.Double line,
                                               Point2D.Double p) {
            double minDist = Double.MAX_VALUE;
            Point2D.Double closePt = new Point2D.Double();
            double dy = line.getY2() - line.getY1();
            double dx = line.getX2() - line.getX1();
            double theta = Math.atan2(dy, dx);
            double length = line.getP2().distance(line.getP1());
            int limit = (int)(length+.05);
            for(int j = 0; j < limit; j++) {
                double x = line.getX1() + j*Math.cos(theta);
                double y = line.getY1() + j*Math.sin(theta);
                double distance = p.distance(x, y);
                if(distance < minDist) {
                    minDist = distance;
                    closePt.setLocation(x, y);
            return closePt;
        private boolean isPointOnLine(Point p) {
            Point2D.Double start = new Point2D.Double();
            Point2D.Double end = new Point2D.Double();
            Line2D.Double line = new Line2D.Double();
            PathIterator pit = path.getPathIterator(null);
            double[] coords = new double[2];
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                        start.setLocation(coords[0], coords[1]);
                        pit.next();
                        continue;
                    case PathIterator.SEG_LINETO:
                        end.setLocation(coords[0], coords[1]);
                        line.setLine(start, end);
                        if(line.ptSegDist(p) < PROXIMITY) {
                            return true;
                start.setLocation(end);
                pit.next();
            return false;
        public static void main(String[] args) {
            ShortPath test = new ShortPath();
            test.addMouseListener(test.ml);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private MouseListener ml = new MouseAdapter() {
            boolean oneSet = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(oneSet) {
                    p2 = p;
                    findShortPath();
                } else {
                    p1 = p;
                    shortPath.reset();
                oneSet = !oneSet;
                repaint();
    }

  • Dispay shortest path in MapViewer

    Hello,
    I had sucsessfully installed MapViewer 9.0.4 and Oracle Spatial 10g.
    here I would like to know how to make a shortest path query between two point in Oracle MapViewer and display it.
    Any help will be appreciated.
    regards
    aziz

    Hi Aziz,
    the next release of MapViewer will support the Network Model including requests ro render shortest paths.

  • Query for finding shortest path

    I know nothing about Oracle Spatial. Just want to know if this query is possible using Spatial.
    Given the following data for undirected weighted graph,
    v1: vertex 1
    v2: vertex 2
    w: weight between vertices v1 and v2(or, distance of edge)
    table name : wgraph
    v1  v2  w
    k   a    2
    m  a    3
    k   c    1
    k   d    4
    c   b    2
    h   d    3
    c   h    3
    h   e    4
    e   b    4
    m  b    6Can I make a query which gives the shortest path from vertex 'a' to vertext 'e' using Spatial?
    If this possible, that query gives the following result. (row-spanning form)
    I think this is almost impossible using just a hierachical query.
    Any method for this in Oracle Spatial?
    spath
    a
    k
    c
    b
    e
    This is not a sort of homework or exam, just my interest.
    Thx in advance.
    Query Your Dream & Future at
    http://www.soqool.com

    yes why not! in your case just create a logical network- called LRS Network and insert your vertices in node- table and additional information plus cost in the link table.
    you can find ways using by dijkstra and A*

  • Computing of the shortest path using a custom cost function in Oracle NDM

    Hi to all,
    I have Oracle 10g R2, I'm working on Oracle Network Data Model. I created a Network (named ITALIA_NET) based on links table (named ITALIA_LINK$) and nodes table (named ITALIA_NODE$).
    Until now I computed the shortest path between two nodes using the 10gR2 NDM Java API, in particular I used the shortestPath() method.
    I know that this method computes the shortest path between two nodes on the base of the values of a field that can be the lenght OR the travel time of the links.
    What I wish to do is compute the shortest path between two nodes with a function that considers ( at the same time ) more parameters and on the base of them returns a path. For example, I want compute the shortest path taking into account these parameters for the links:
    travel times of links
    gradient links
    tortuosity links
    Infact, I have for each link the costs of: travel time (for example 3 minuts for cross the link), gradient (for example, the link has 2% of gradient) and tortuosity (for example, the link has two curves of 60° of angle).
    Do you have any idea how I can implement this?
    Are there other ways for reach this objective?
    I hope I explained well my objective.
    Thank you very much to all in advance.

    _1) If I convert the values of the other cost columns into the values of the primary cost column (time is ok), what is the formulation for do this conversion?_
    The modeling part is the most difficult part. I am not sure if there is a universal conversion formula between two different costs.
    One recommendation is to use time as your primary cost.
    For any other secondary costs, collect some data (or from some published statistics) on how these costs affect the travel time (based on the actual speeds wrt to gradients and tortuosity).
    I am not an expert on this. Maybe asking questions like,
    Q. how will a road of gradient = 10 deg affect the speed, uphill and downhill compared to the speed limit?
    Once you have a good estimates on the speeds, you can compute the travel times as the distance/length of the link is known. The same applies to tortuosity,
    Q. how will roads with 30/60/90 deg angles affect the travel speeds compared to the speed limit?
    Assuming you are using something like the speed limit as you normal travel speed to compute your travel time.
    _2) After conversion, how can I combine these columns?_
    Say if you have done the conversion part in Step 1, you have 3 costs,
    cost1, cost2, and cost3
    You can create a view on the link table with the combined link cost as (cost1+cost2+cost4) or
    you can create a new column that sums up the costs you want and use it as the link cost.
    hope it helps!
    jack

  • Aco  implemenataion for shortest paths.

    has anyone used ant colony optimization algorithm for finding shortest paths other than for the tsp? please i need some help and advice. thanks

    sorry for not being specific and the insubsequent reply. am just doing some research on aco, i want to try and implement it for best bath planning on a map/graph. I've been looking around for some example on such and noticed that this algorithm is mainly used for tsp problem which got me questioning the possibility of my task. I just want to know if it is definitely possible with aco as i will give it a go in this case. Implementing this algorthm successfully is the main challenge of my project so i cannot contemplate another algorithm option. Thanks for your time.

  • Shortest path problem in ABAP

    Hi experts,
    Is it possible to write the code for the "Shortest path problem" in ABAP?If yes, what is the code?
    Moderator Message: Don't expect members to spoon-feed you
    Edited by: Suhas Saha on Jul 25, 2011 11:13 AM

    Hi munish,
    I dont think there is any thing wrong with the ABAP code.
    Try testing your ABAP mapping using transaction code SXI_MAPPING_TEST in XI.
    Enter the Details asked and then enter TEst data in XML format.. 
    Also, you can make use of the Trace element to find out if there is any thing wrong with the code.
    Include the following Statements after every step in the ABAP code to ensure that the particular step is completed successfully.
    data : l_trace type string.
    concatenate l_trace '<Message you want to display>' into l_trace.
    trace->trace(level = '<level>'
    message =l_trace).  
    The trace is visible in SXMB_MONI (click on "Trace" in the left pane to view).
    using this you will get to know i the code is functioning as desired.
    Regards,
    Yashaswee.

  • Air Application URL Path Issue

    I am trying to invoke a  content of the file which is in shared folder from Air application.
    Version : Flash builder 4.5,Flex3.6 sdk and Air 2.7.
    for this am using the below code..
    var request:URLRequest = new URLRequest();
    //request.url = ('file:///c:/params.txt'); - This is working fine
    request.url = ('file:///172.20.188.25/Share/chk/Property/params.txt');  // its not working
    trace("Unable to load URL: " + request);
    var variables:URLLoader = new URLLoader();
    variables.dataFormat = URLLoaderDataFormat.VARIABLES;
    variables.addEventListener(Event.COMPLETE, completeHandler);
    try
    variables.load(request);
    The same part of code ,I tried in Flex application is working .but in Air application its not working.
    Its urgent requirement,If any one know the way to resolve this path issues.
    Kindly let us know.
    Thanks in Advance !!

    I tried in the following URL but no use ..
    its throwing ioError and textError and stream error.
    1.file:///172.20.188.25/Share/chk/Property/params.txt
    2.http://172.20.188.25/Share/chk/Property/params.txt
    3. //172.20.188.25/Share/chk/Property/params.txt
    Is there any other solution for this issue ?

  • Leopard + Numpy + Scipy: Path Issues Remain

    +This post has been cross-posted on the pythonmac-sig mailing list.+
    I've been reading about the python path issues with Leopard and have tried the different methods outlined for addressing this problem with no good result. Currently I am using a combination of .pth files and a modification to my ~/.profile. One nagging problem is that SUDO commands do not maintain these settings. When I install wxPython, these go into the /System folder, not my /Library/Python folder. Also, when installing scipy, numpy.distutils.core cannot be found.
    sudo python scipy_dir/setup.py install
    I've installed numpy 1.0.4 and this is placed in /Library/Python/2.5/site-packages. I've also installed the MacPython from python.org. When running python from a Terminal window, the correct version of numpy gets loaded (1.0.4). However, as has been documented before, sudo overrides these settings, so when I attempt to install scipy, the following error shows up:
    Traceback (most recent call last):
    File "setup.py", line 55, in <module>
    setup_package()
    File "setup.py", line 29, in setup_package
    from numpy.distutils.core import setup
    ImportError: No module named numpy.distutils.core
    Has anyone found a way around this?
    Just for good measure, I've included my current sys.path (after a sudo call):
    ['/code/libs/scipy-0.6.0', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-s criptpackages', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages' , '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ wx-2.8-mac-unicode']

    Hi, newbie730
    On my system, the numpy module is not found in
    /System/Library/Frameworks/Python.framework/Versions/2.5/lib
    but rather in
    /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python ...
    perhaps your sys.path is missing an element?
    To elaborate a bit more, the solution that worked for me was to either just use the default version of python (/usr/bin/python), in which case numpy works just fine with no further tweaking, or if I want readline support to use the interpreter from fink (/sw/bin/python), and set the environment using the PYTHONPATH variable:
    (all these should be exported)
    # for python:
    PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/p ython/:$ROOTSYS/pyroot:$ROOTSYS/lib
    # 'base' files, including numpy and scipy installed by apple + ROOT stuff
    PYTHONPATH=$PYTHONPATH:/Documents/Code/python #add my own modules
    PYTHONSTARTUP=/Users/#####/.pystartup
    PYTHONDOC=/sw/share/doc/python25/html
    I'm not sure if that answers your question...
    Caleb

  • Pathing issues in Flash CC

    I believe I have some pathing issues and was wondering how I can change the pathing so that is can be view publicly. The problem is my videos are being played from my local folder and can't be access via web browser for other users.

    It's in the code area, and I tried pasting it (didn't show anything) and then executing the code, and it didn't do anything.
    I then tried creating a text area on the page, and went to the Edit menu - and "Paste Special" was the only available option. So I tried that, and it says "Source: Unknown Source" and the only option I have is to Cancel.
    I then went into Flash CS6, and copied a line of code from that. I tried pasting it into the Flash CC 2014 actions console, and it did nothing. I then went back to my text area (still in Flash CC 2014) and it pasted the code in there fine. 
    So, it looks like I still cannot copy from or paste into the actions panel Flash CC 2014, which is what I need. But, maybe this sparks another idea? Thanks for your help, I appreciate it.

  • Shortest Path Java Code

    Hi
    I have created a topological network in Oracle Spatial and now
    I am trying to find the shortest path between two nodes.
    Is there a sample java code (or instructions) that connects to the database
    and gets that information?
    Thank u

    Oracle Spatial NDM Java API has several shortest path analysis functions. A simple example is as follows.
    // establish JDBC connection: you need specify dbURL, user1, password1
    OracleDataSource ods1 = new OracleDataSource();
    ods1.setURL(dbURL);
         ods1.setUser(user1);
         ods1.setPassword(password1);
    Connection conn1 = ods1.getConnection();
    // read in network, netName is the name of your network in the database
    Network net = NetworkManager.readNetwork(conn1, netName);
    // perform shortestPath analysis
    Path path = NetworkManager.shortestPath(net, startNodeID, endNodeID);
    // then from Path interface, you can access its constituent link/node information
    }

Maybe you are looking for