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.

Similar Messages

  • Fitness for Shortest path using a genetic algorithm

    Hi.
    I have this problem:
    I'm doing a program that has a map and two points. the map has wall that are not valid positions.
    I have used a A* algorithm to calculate the shortest path and is working fine.
    now i'm implementing a genetic algorithm to solve the problem but i'm not having sucess.
    My genetic operator are directions (left, right, up and down).
    I'm not being able to find a goodfitness function to solve the problem.
    can someone tell me a god function or here I can found information about that?
    I have been searching on google and I have not yet had sucess.
    I have tryed two diferent fitness tecniques:
    - add 1 for each step and if it finds a wall or gets out of the map add the maximum value (mapsize*mapsize).
    - the other one is add the valid steps and if it finds a wall or gets out of the map add the number of necessary steps to gets to destination. the valid steps has a weight of 30% and the necessary steps has a weight of 70% (i have tryed to use diferent weight).
    Can someone help me?
    thanks

    How about adapting your TSP code as follows. Your graph G(V, E) has two special vertices: v_s and v_d (start and destination). Let a candidate solution consist of a permutation of V\{v_s, v_d}u{v_m} where v_m is a new marker vertex whose purpose is to allow you to treat part of the candidate solution as irrelevant. Given candidate solution v_0 v_1 v_2 ... v_n v_m v_n+1 ... the weight is c(v_s, v_0) + c(v_0, v_1) + ... + c(v_n-1, v_n) where c(v_a, v_b) is the cost of the edge ab.

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

  • Shortest path between two arbitrary point in the network

    Hi All,
    In oracle NDM, it's possible to find shortest path between two nodes (e.g. using SDO_NET_MEM.NETWORK_MANAGER.SHORTEST_PATH), but I need to find shortest path between 2 points which are on the network edges. I suppose I should use (Interface SubPath) in network java apis. However I want to do it via PLSQL api. Should I code it myself or there exists a function?
    Any help is appreciated.
    Edited by: Fa on Dec 15, 2011 2:51 AM

    pritamg wrote:
    I have to build an application in which the user will draw the graph by creating nodes and edges.and then the start node will be marked.Then the shortest paths to other nodes will be displayed.Give me any possible clue how to start.I am in deep deep trouble.I have to use Dijkstra's Algorithm.
    please help some one...pleaseDo you know Dijkstra's Algorithm for shortest path? I believe that one was also called the traveling salesman problem. You can easily Google to find out what it is.
    Did you listen to your instructor when he/she did his/her lectures on recursion and halting contitions? If not, then please go talk to him/her and read your book, the forum is not a place to try to learn a basic concept that you should have paid attention in class for the first time.
    If you have code and you have specific questions post them and we will be glad to help, but we are not here to develop your homework solutions for you, no matter how that may affect your future.

  • Ant Colony Algorithm(ACO)  for best path searching on a graph

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

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

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

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

  • Shortest path for Maze !

    Sorry guy i know this topic look familiar but i have been "turn the whole internet updown" but it does seen to have see any source code for maze using Dijkstra's Algorithm. I have try the back-tracking method but i realise that they do not lead to the shortest paths if the maze is too complicated. I even have 12 different different test but sad nope of them took the shortest paths in this maze . I hope some one can help me .
    The original Maze
    =================
    +---------+-------------+---+
    |         |             |   |
    +-+ + +---+-------+ +---+ +-+
    |   |     |             |   |
    +---+ +-+-+ +-+-+ + + +-+-+ +
    |       |     |     |     | |
    +-+ +-+ + +---+---+-+ + +-+ |
    | |  v    |   |   |   |     |
    | +-+ +-+ | +-+-+ + +-+ +-+ |
    | |   |   |             |   |
    | | +-+---+-----+---+-+ | + |
    | | |           |   |   | | |
    | + | +---+-+ +-+ + + +-+ | |
    |   |  X  |       |       | |
    +---+-----+-------+-------+-+
    Robot location is at X :7 Y :5
    The goal is at location X =13  Y =7
    this is the Test calling solveTest1 method
    =============================
    +---------+-------------+---+
    |.........|.............|...|
    +-+.+.+---+-------+.+---+.+-+
    |...|.....|******* ***  |...|
    +---+.+-+-+*+-+-+*+*+*+-+-+.+
    |.......|***  |  ***|*....|.|
    +-+.+-+.+*+---+---+-+*+.+-+.|
    |.|..v****|   |   |***|.....|
    |.+-+.+-+.| +-+-+ +*+-+.+-+.|
    |.|...|...|        *****|...|
    |.|.+-+---+-----+---+-+*|.+.|
    |.|.|*********..|***|***|.|.|
    |.+.|*+---+-+*+-+*+*+*+-+.|.|
    |...|***  |  *****|***....|.|
    +---+-----+-------+-------+-+
    this is the Test calling solveTest2 method
    =============================
    +---------+-------------+---+
    |.........|.............|...|
    +-+.+.+---+-------+.+---+.+-+
    |...|.....|*******.***  |...|
    +---+.+-+-+*+-+-+*+*+*+-+-+.+
    |..*****|***  |..***|*....|.|
    +-+*+-+*+*+---+---+-+*+.+-+.|
    |.|**>.***|...|...|***|*****|
    |.+-+.+-+ |.+-+-+.+*+-+*+-+*|
    |.|...|   |........*****|***|
    |.|.+-+---+-----+---+-+.|*+.|
    |.|.|*********  |***|...|*|.|
    |.+.|*+---+-+*+-+*+*+.+-+*|.|
    |...|***  |  *****|*******|.|
    +---+-----+-------+-------+-+
    this is the Test calling solveTest3 method
    =============================
    +---------+-------------+---+
    |         |             |   |
    +-+ + +---+-------+ +---+ +-+
    |   |     |***********..|   |
    +---+ +-+-+*+-+-+ + +*+-+-+ +
    |       |***..|     |***..| |
    +-+ +-+ +*+---+---+-+ +*+-+ |
    | |  >****|   |   |   |*****|
    | +-+ +-+.| +-+-+ + +-+ +-+*|
    | |   |...|             |***|
    | | +-+---+-----+---+-+ |*+ |
    | | |*********..|***|   |*| |
    | + |*+---+-+*+-+*+*+ +-+*| |
    |   |***  |..*****|*******| |
    +---+-----+-------+-------+-+
    this is the Test calling solveTest4 method
    =============================
    +---------+-------------+---+
    |         |             |   |
    +-+ + +---+-------+ +---+ +-+
    |   |     |***********..|   |
    +---+ +-+-+*+-+-+ + +*+-+-+ +
    |..*****|***..|     |***..| |
    +-+*+-+*+*+---+---+-+ +*+-+ |
    | |**>.***|   |   |   |*****|
    | +-+ +-+.| +-+-+ + +-+ +-+*|
    | |   |...|             |***|
    | | +-+---+-----+---+-+ |*+ |
    | | |*********  |***|   |*| |
    | + |*+---+-+*+-+*+*+ +-+*| |
    |   |***  |..*****|*******| |
    +---+-----+-------+-------+-+

    public boolean solve (int row, int column) {
          boolean done = false;
          if (valid (row, column)) {
             grid[row][column] = 3;  // cell has been tried
             if (row == grid.length-1 && column == grid[0].length-1)
                done = true;  // maze is solved
             else {
                done = solve (row+1, column);  // down
                if (!done)
                   done = solve (row, column+1);  // right
                if (!done)
                   done = solve (row-1, column);  // up
                if (!done)
                   done = solve (row, column-1);  // left
             if (done)  // part of the final path
                grid[row][column] = 7;
          return done;
       }  // method solvea typical code which i got from the net .I realise it was commonly use.

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

  • 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

  • Network LOD support for All Paths between 2 nodes

    In the in-memory Network API, there is a method NetworkManager.allPaths. This method returns available paths between 2 nodes with possible constraints. I am looking for a similar method in the LOD NetworkAnalyst class and am not finding it. Is there something similar?
    Or, here is what I want to do, and maybe there is a better way to do it. I am using NDM to data-mine our roadway inventory. Its a big network, whole state of Ohio, all roads--both local and state. One of the things I am trying to identify are what we call co-located routes. These are routes that have multiple names, for example, the ohio turnpike is both Interstate 80 and 90 on the same bed of road. In our line work, where these routes are co-located, we would only have a record for 80. The portion of 90 that we would have would be only in the case where it is NOT co-located with 80; in other words, 90 has a gap where it is co-located with 80. This is true for all our roads. In this case, we call 80 the primary, and 90 the secondary. We can have infinite secondaries (our worst case scenario is 6 routes overlapping). My situation in many cases, is I know that a route becomes secondary, I know how long the secondary section is, but I don't know what the primary is, so I want to discover it.
    Given these assumptions, I should be able to ask for all paths between 2 nodes that exactly match a cost (the overall length of the overlap). This should be simple with NDM. I provide a begin node, an end node, and a target cost, possible some traversal constraints, and it returns me the candidate paths. I thought that NetworkAnalyst.withinCost would do this, but as I discovered from the Stored Procedure docs, it returns the shortest path within the given less than or equal to the given cost--not necessarily the path I am looking for.
    Any advice? FYI, I am using Oracle 11GR2.
    Thanks, Tom

    So what I have come up with so far, is that the NetworkAnalyst trace methods provide this type of functionality. For example, with traceOut, I provide a start node, distance and some traversal constraints, and it returns me all paths less than or equal to the specified distance. What was throwing me a little with this method was the application of the LODGoalNode. I was thinking that the goal node would allow me to specify a particular node to be a requirement for the entire path such that a resulting path would have my start node, and end on a particular goal node with links in between. That IS NOT how it works. The LODGoalNode.isGoal is tested for EACH link that is part of a potential path, and only if this method returns true, is it added to the resulting path list.
    In my case, if I specified a start node and implemented the LODGoalNode.isGoal method such that it tested the provided end node for equality to my target node, the result would be that only links containing that specific goal node in the link. Anyway, so in my implementation, I leave the goalNode of the traceOut method null.
    So I have a new question. Is there a way to test when a path has been found, and then apply some constraints on it (PathConstraint)? This would be useful in cases where you get many paths returned to you, but in addition to a maximum distance constraint, you also want to apply for example a minimum distance on the resulting path, or that this is only a valid path if it ends on a particular node. Maybe there is a way to do this, and I haven't figured it out yet. The old AnalysisInfo class used to have a way to query the current path links and nodes, that would be useful in the LODAnalysisInfo class to help accomplish this perhaps? This feature isn't critical, because I can filter the list of paths returned from traceOut on my own after they are returned, but it would add some efficiency, especially when a large amount of paths are returned.
    Thanks, Tom

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

  • Shortest path problem

    hello,
    We have a street-layer (spatial). Now we should calculate the shortest path between two nodes. Does Oracle assist in this? Has anybody some experiences with this problem?
    Any help will be appreciated.
    regards
    Anna

    Well, I know there are several algorithms for this problem, but I wanted to know, if and how Oracle assist�s in this point. I get an answer from Oracle, that 10g include such functionality and now I am waiting on it.
    Thanks for your try to help.
    Monika-Anna

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

Maybe you are looking for

  • CD/DVD Drive Failure?

    Hello. I have a Pavilion dv9700 notebook running Windows 7. My problem is that I think my CD/DVD drive has failed. The computer won't read any disks, it doesn't even spin the disk as though it's trying to read it. We've tried to update the driver whi

  • How to update and delete records in a text file?

    Hi, I had a text file in which contains records line by line with ',' as delimiter as I use stringtokenizer and vector to read the data. The format in the text file likes: Name, Sex, Age. I want to add 2 functions: (1) update the record by name, sex

  • OS X Lion crashes trying to print from Safari, Pages, Acrobat, Word and Excel

    My OS X Lion crashes while trying to print in Safari, Pages '09 (4.1), Acrobat, Word and Excel. It works in Adobe CS5 Photoshop, Illustrator, InDesign, Numbers '09 (2.1), Apple Mail, and Preview. I'm printing to a Dell 3130 color laser printer.

  • Problem when creating Database:

    There are two problems, which I faced during creation of database. When creating database with Oracle Database Assistant. One when creating pre tuned database from CD. And second when creating customized database giving options your self. Problem # 1

  • MobileIconRenderer not available

    In the code below I get the following error: Could not resolve <s:MobileIconItemRenderer> to a component implementation. Details.mxml /Music/src/com line 11 Flex Problem The component is part of a module. Any ideas why MediaIconRenderer is not availa