Java path finding help

Hello,
I'm at present working on a route finding system for the london underground as a MIDP application in Java.
I have a vector of vectors data structure to store the stations as nodes and lines as edges respectively but need a shorest path algorithm to search from one station to the next taking into account line changes.
Dijkstra's algorithm seems to be the best solution but hard for me to implement.
Any help on this would be most appreciated.
Thaxs.
ash

I found Dijkstra's algorithm extremely easy to implement by a recursive routine. I found it easiest to work backwards (it simplifies setting the route direction).
Each node holds a field from distance from the destination, set them all to infinity initially. The node also has a field for next node on the route.
Then you have a method of the node which offers a route to a node. The arguments are the next node in the route and the resulting distance. The method does nothing if the route offered is longer than one it already has. Otherwise it sets the new length and route to the one on offer and offers itself to all neigbouring nodes.
Then you just call it on the destination node with a distance of zero and a null route.
Something like this;
class Link {
      Station start;
       float length;
class Station {
     Float distance;
     Link nextStep;
      ArrayList  incomingLinks;
    public void djikstra(float newDistance, Link route) {
          if(distance == null || distance.floatValue() > newDistance) {
                distance = new Float(newDistance);
                nextStep = route;
                for(Iterator it = incomingLinks.iterator(); it.hasNext();) {
                    Link incoming = (Link)it.next();
                    incoming.start.djikstra(newDistance + incoming.length, incoming);
      }(This assumes that if a link is two-way two Links must be created).

Similar Messages

  • Oracle Universal Installer cannot be run... getting this error due to Java path. Pleath help.

    Hi Experts,
    Trying to Deinstall the OBIEE 11g. OUI is not launching... after digging the issue find out that "Java RunTime Environment was not found".
    But Java software is available at the specified path.
    "C:\DOCUME~1\user\LOCALS~1\Temp\OraInstall2013-09-05_01-10-08PM\jre\bin\javaw.exe"
    Can you please help me on this... The complete error is...
    Oracle Universal Installer
    The Java RunTime Environment was not found at C:\DOCUME~1\v859971\LOCALS~1\Temp\OraInstall2013-09-05_01-10-08PM\jre\bin\javaw.exe. Hence, the Oracle Universal Installer cannot be run.
    Please visit http://www.javasoft.com and install JRE version 1.3.1 or higher and try again.
    OK  
    Arjun

    Hi Srini,
    I have tried as you mentioned like installing Java in C:\Java... and I have tried the by setting the JRE_LOCATION of local path. No use of it.
    tried with -jreloc and setting the java path in environment variables too.
    As I understand, the problem i have seen at files copied path is not expected as required. Please see the path below...
    C:\DOCUME~1\v859971\LOCALS~1\Temp\OraInstall2013-09-06_03-36-31PM\jre\bin\javaw.exe.
    After running the Setup.exe -deinstall... temporary folder is creating with timestamp and all the required files are coping here...
    "jre" folder also created and copied required java files directly into jre folder, but not in jre\bin folder.
    folder path is like this
    C:\DOCUME~1\v859971\LOCALS~1\Temp\OraInstall2013-09-06_03-36-31PM\jre\javaw.exe.
    Setup application is expecting jre\bin\javaw.exe, but folder structure is created as jre\javaw.exe. There it is coming the issue.
    I have even tried with copying all the files into bin folder and executed the setup.exe, it again creating a new temporary file
    not able to resolve it...

  • Help on path finding

    Hello everyone!
    Help me please!
    Have you ever played games like Baldur's gate or Diablo or classic adventure games (like Monkey island)?
    What I'm saying is:
    I'm trying to implement a way to move my character, on a 2D space, to the point I clicked on.
    If there is no obstacle between the start and the finish points, I can make it work pretty easily (I just let the charachter walk the straight line connecting the points).
    The problem is when I introduce obstacles.
    I'm trying to implement the A* algorithm for the path finding process.
    Since the character and the obstacles lay on a 2D plane not divided into tiles or any sort of sub-division, it is quite hard to calculate a path.
    What I thought of doing is:
    when I click on a destination point, I create a 2D grid surrounding the character, at its actual position, and the destination point.
    The intersections between the horizontal and the vertical lines of this grid, will be the possible nodes of the path to the destination. (I hope it's clear).
    The A* will calculate the best path among these nodes, considering whether a node is reachable (i.e. not overlapping an obstacle) or not.
    I still haven't implemented it, so it's just an idea, and I don't even know if it works!
    Is it possible there is no other way of doing that?
    How do the games I mentioned above work?
    My problem is finding a way to determine the possible nodes (2D points on the 2D plane) for the A* algorithm to work on.
    Please help, I'm stuck.
    Any suggestion?
    Thank you!
    P.S: If you need me to make it more clear, I'll give it a try!

    So far as I've tested it they haven't gotten stuck.
    The best way I can think of to do it is with the Line2D.Double class.
    - I draw a line between me and the enemy
    - create two lines that are equal to that first line
    - rotate the first line, from the enemy, to the left
    - rotate the first line, from the enemy, to the right
    - if both still intersect the obstacle, I rotate the two again
    - if one of them no longer intersects the obstacle, that new line becomes my path
    Once the clear path is found, I can use the endpoint of that line as the destination, rather than saying that MY coordinates are the destination. It takes a lot of math figuring so it gets messy written out, but in words it's very clean :)
    For simplicity you could try:
    - if he hits an obstacle do the following:
    - draw a line between the entity and the center of the obstacle
    - if you're on the left side of that line, make him turn left 90 degrees
    - if you're on the right side, turn right 90 degrees
    Based on how you're creating your obstacles you could think further how you want to do it, like tell them to move in that direction a set distance, that sort of thing.
    Or you could give them set paths to follow, that's another solution, and just have them be able to aim at you freely to fire, provided that's how they attack.

  • Help Using Path Finding Code

    Hi all.
    I found some open source code which implements the A Star algorithm to achieve path finding for the purpose of navigating something in a game (although it could really be used for anything). Problem is, I can't get it to work. I've e-mailed the author but no reply yet so I was hoping someone could shed some light on my situation.
    The code is meant to find a path on a 2 dimensional grid filled with obstacles using the following methods:
    PathFinder star = new PathFinder(grid);
    Path p = star.findShortest(startRow,startCol,goalRow,goalCol);
    I've made a simple Test class with a small 2D array but when I compile the code I recieve the error:
    Incompatible types.
    Found: int.
    Required: Test.Path
    on Path p = star.findShortest(1,1,2,2);
    I don't understand this error at all. The findShortest method takes 4 integers and I'm passing it 4 integers! Any ideas what this error means?
    Here's my Test class:
    import java.util.*;
    import javax.swing.plaf.basic.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.filechooser.*;
    import java.util.Random;
    public class Test
            public static void main(String args[])
                    Test test = new Test();
                    test.run();
           public final static class Path
                    /** 2 for down, 0 is up, 1 is right and 3 is left */
                    public int giveMove() {
                        if (size() < 2)
                            return -1;
                        Position last = (Position)positions.get(size() - 1);
                        Position forlast = (Position)positions.get(size() - 2);
                        if (forlast.col - last.col == 1)
                            return 2; //down
                        else if (forlast.col - last.col == -1)
                            return 0; //up
                        else if (forlast.row - last.row == 1)
                            return 1;//right
                        else if (forlast.row - last.row == -1)
                            return 3; //left
                        return -1;
                    /** list of positions */
                    public List positions;
                    public int getCost() { return positions.size() - 1; }
                    public int size() { return positions.size(); }
                    public void add(Object o) { positions.add(o); }
                    /** add (r,c) to the path */
                    public void add(int r, int c) {
                        positions.add(new Position(r,c));
                    /** get first position */
                    public Position head() { return (Position) positions.get(0); }
                    public Path(ArrayList positions) { this.positions = positions; }
                    public Path(Position initial) {
                        positions = new ArrayList(1);
                        positions.add(initial);
                    public Path(int cap) { positions = new ArrayList(cap); }
                    public void set(Position front, Path old) {
                        positions.add(front);
                        Iterator i = old.positions.iterator();
                        while (i.hasNext())
                            positions.add(i.next());
            /** position on the grid */
           public static final  class Position
                    public int row, col;
                    public Position(int row, int col) {
                        this.row = row; this.col = col;
            public void run()
                    System.out.println("Test");
                    PathFinder star = new PathFinder(grid);
                    for(int counter = 0; counter < grid.length; counter++)
                            for (int j=0; j < grid[counter].length; j++)
                                    grid[counter][j] = 0;
                    Path p = star.findShortest(1, 1, 2, 2);
         private static int[][] grid = new int[2][2];    
    } Here's the PathFinder class I downloaded:
    import java.util.*;
    import javax.swing.plaf.basic.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import javax.swing.filechooser.*;
    import java.util.Random;
    public final class PathFinder {
        /** the map grid to look on */
        private final int [][] grid;
        /** keep distances to each position here */
        private final int [][] distances;
        /** is gridposition (r, c) empty (empty is -1) ? */
        private boolean isEmpty(int r, int c) {
            return grid[r][c] == -1 ;
        /** pathfinder for grid */
        public PathFinder(int[][] grid) {
            this.grid = grid;
            this.distances = new int [grid.length][grid.length];
        /** clear distances */
        private void clear() {
            for (int i = 0 ; i < distances.length ; i++)
                for (int j = 0 ; j < distances.length ; j++)
    distances[i][j] = Integer.MAX_VALUE;
    /** position on the grid */
    public final static class Position {
    public int row, col;
    public Position(int row, int col) {
    this.row = row; this.col = col;
    /** path from start to a certain position */
    public final static class Path {
    /** 2 for down, 0 is up, 1 is right and 3 is left */
    public int giveMove() {
    if (size() < 2)
    return -1;
    Position last = (Position)positions.get(size() - 1);
    Position forlast = (Position)positions.get(size() - 2);
    if (forlast.col - last.col == 1)
    return 2; //down
    else if (forlast.col - last.col == -1)
    return 0; //up
    else if (forlast.row - last.row == 1)
    return 1;//right
    else if (forlast.row - last.row == -1)
    return 3; //left
    return -1;
    /** list of positions */
    public List positions;
    public int getCost() { return positions.size() - 1; }
    public int size() { return positions.size(); }
    public void add(Object o) { positions.add(o); }
    /** add (r,c) to the path */
    public void add(int r, int c) {
    positions.add(new Position(r,c));
    /** get first position */
    public Position head() { return (Position) positions.get(0); }
    public Path(ArrayList positions) { this.positions = positions; }
    public Path(Position initial) {
    positions = new ArrayList(1);
    positions.add(initial);
    public Path(int cap) { positions = new ArrayList(cap); }
    public void set(Position front, Path old) {
    positions.add(front);
    Iterator i = old.positions.iterator();
    while (i.hasNext())
    positions.add(i.next());
    /** gives the move to take for the shortest path from startRow to startCol
    * 0 up, 1 right, 2 down, 3 left
    * -1 if no move possible
    public final int findShortest
    (int startRow, int startCol, int goalRow, int goalCol) {
    clear();
    Position initial = new Position(startRow, startCol);
    //LinkedList list = new LinkedList();
    Position goal = new Position(goalRow, goalCol);
    BinaireHoop list = new BinaireHoop(200, new Path(goal), goal);
    list.add(new Path(initial));
    Position [] successors = new Position[4];
    int trie = 0;
    for ( ; ! list.isEmpty() && trie < 10000 ; trie++) {
    Path first = (Path) list.remove();
    Position firstPos = first.head();
    int r = firstPos.row; int c = firstPos.col;
    if (r == goalRow && c == goalCol) {  //goal found !             
    return first.giveMove();
    } else {
    int successorsCount = 0;
    if (isEmpty(r-1,c)) {
    successors[successorsCount++]
    = new Position(r-1, c);
    if (isEmpty(r+1,c)) {
    successors[successorsCount++]
    = new Position(r+1, c);
    if (isEmpty(r,c-1)) {
    successors[successorsCount++]
    = new Position(r, c-1);
    if (isEmpty(r,c+1)) {
    successors[successorsCount++]
    = new Position(r, c+1);
    while (successorsCount-- > 0) {
    Position succ = successors[successorsCount];
    int newPathCost = first.getCost() + 1;
    //add newPath if shorter than other path to this position
    if (distances[succ.row][succ.col] > newPathCost) { //shorter
    distances[succ.row][succ.col] = newPathCost;
    Path newPath = new Path(newPathCost + 1);
    newPath.set(succ, first);
    //add path to binary heap
    list.add(newPath);
    } // else longer: discard
    return -1;
    There's also a BinaireHoop class which the PathFinder class uses. I'll post that code if anyone thinks it's relevant but the error appears to be soley on my implementation. The Path and Position and just small subclass which for the sake of quickness I just placed into my Test class too instead of into a new class to themselves.
    Any thoughts appreciated! I would really like to get this working =)
    Thanks.

    Thanks for your reply. Doh, totally missed that one =)
    Anyway, I got the code working but it's still very buggy. I think this must just be a problem with the PathFinder class I downloaded.
    I create a 2D array
          int[][] array = {       
                                  {-1, -1, -1, -1, -1, -1, -1, -1},          
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1},
                                  {-1, -1, -1, -1, -1, -1, -1, -1}
                          };and choose starting and goal coordinates
    int p = star.findShortest(1, 1, 2, 2);The PathFinder will generate the coordinates to move to (I just stuck it all in a loop and updated the starting coordinates as appropriate to lead me to the goal). This is great!
    However, there seem to be a lot of bugs when I introduce "occupied squares". Basically, -1 in the array means that that square is empty whereas anything else means its full and the path finder should, in theory, generate a path around these obstacles. This isn't working correctly though.
    Sometimes a path wil be found around the obstacle, sometimes the path will go straight through it, and many times it just throws an array index out of bounds exception error!
    Anyone got any ideas? Or does anyone have any examples of a working path finder? =)
    Cheers

  • Path finding based on an image

    I know its possible to create a path finding algorithm based on an image... That is, if the color map is blue then there is water, if it is brown then there is land. So detection of land and water is not the problem.
    What I want to know is, is there an easy way to set up a path finder aside having a for loop try all the possibilities? The loop should follow logical paths rather than iterate through each turn...

    I'd try an image processing forum. This forum is typically for Java-specific issues and there might not be that many people who've done this here. Sorry I couldn't help. Have you read some image processing books?

  • Path Finder in a 2D Grid Map With Different Terrain Types

         I have been thinking for a while on path finding game algoritms and I can up with one idea witch I want to publish. The goal of my project is when I have a 2 dimensional grid map where squares can have different movement cost, like in Civilization II, to find the shortest way from one point in the map to another. I've used the Breathed First Search Engine. If you are not familiar to this search engine it is better to read about it first because I am not fcusing on it and I assume that you now how it works. You can read about it at the book "Practical Artificial Intelligence Programming in Java" writen by Mark Watson, witch is freely distributed at www.markwatson.com.
         Actually the idea of this 2D grid path finder is to use a third dimension witch have a size equal to the highest movement cost among all terrain types. This helps solving the problem with the different movement cost of the squates. By adding this abstract third dimension it is posible to use the Breadth First Search Engine.
         I this example the movementcost of a terrain type is always the same, no matter from witch square to with are you going (like in Civilization II but I haven't included roads or railroads). For example if you want to go from one square A to another square B with movement cost X (A and B are attached) you must go "up stairs" in the third dimension X - 1 times and then move to square B. But when you step on square B you are again at the lowest floor. So if you want to come back to the previous square A and it have movement cost Y first you must go floor Y and then jump in square A. And now you are again at the lowest floor at square A. When you move from one square to another you go always at the lowest floor. This is the way I handle with different movement costs.
         When you find the path to the goal point it is in 3 dimensions. So you must just project it in the 2D map and that's all you have the shortest path.
         I am sure this is not the best way to code this search engine but this is just the first scratch with no optimisation and so on. If I make a 100x100 randomly generated map it takes on my configuration(400Mhz Pentium II CPU with ASUS P2B MotherBoard on 100 MHz and 256 MB SD RAM on 133 MHz but because of my MB on 100MHz) around 1000 miliseconds (1000 miliseconds = 1 second) to find the shortest path from (1, 1) to (100, 100) witch is pretty good compare to the goTo function in Civilization II witch does not finds the shortest path at all and have made hundrets of gamers angry. This is amazing that nowadays there are so many games with bad path finding.
         This project includes:
    1. The PathFinder class witch does the jub.
    2. The Map class witch has a generator for a random map in it.
    3. The class TerrainType, every square on the map is based on this class.
    4. The class TerrainTypes witch is the set of all terrain types used in the map.
    5. The class PathFinderTest witch just test the path finder.
    To test this project put all files in one directory and run PathFinderTest.java.
    Map.java:
    import java.util.Vector;
    import java.util.Random;
    //This class just creates a random map and keeps it. I will not comment on this.
    class Map {
      //here is kept the information about the terrain types placed in the map. Where
      //every terrain type has a specific movement cost.
      private int[][] terrain;
      public TerrainTypes terrainTypes;
      private int landMass;
      private int width;
      private int height;
      private int highestMovementCost;
      public Map(int aWidth, int aHeight) {
        width = aWidth;
        height = aHeight;
        terrainTypes = new TerrainTypes();
        highestMovementCost = terrainTypes.getHighestMovementCost();
        terrain = new int[width][height];
        landMass = 0;
        generateRandomMap();
      public void clearGoalAndStartLocFromWater(int sx, int sy, int gx, int gy) {
        terrain[gx][gy] = 0;
        terrain[sx][sy] = 0;
      private void expandWater() {
        int waterConstant = 40;
        int waterExpansion = 2;
        int[][] moreWater = new int[width][height];
        Random randomizer = new Random();
        for (int t = 0; waterExpansion > t; t++) {
          for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
              if (i + 1 >= 0 && j >= 0 && i + 1 < width && j < height) {
                if (terrain[i + 1][j] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j] = 1;
              if (i + 1 >= 0 && j - 1 >= 0 && i + 1 < width && j - 1 < height) {
                if (terrain[i + 1][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j - 1] = 1;
              if (i >= 0 && j - 1 >= 0 && i < width && j - 1 < height) {
                if (terrain[i][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i][j - 1] = 1;
              if (i - 1 >= 0 && j - 1 >= 0 && i - 1 < width && j - 1 < height) {
                if (terrain[i - 1][j - 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j - 1] = 1;
              if (i - 1 >= 0 && j >= 0 && i - 1 < width && j < height) {
                if (terrain[i - 1][j] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j] = 1;
              if (i - 1 >= 0 && j + 1 >= 0 && i - 1 < width && j + 1 < height) {
                if (terrain[i - 1][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i - 1][j + 1] = 1;
              if (i >= 0 && j + 1 >= 0 && i < width && j + 1 < height) {
                if (terrain[i][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i][j + 1] = 1;
              if (i + 1 >= 0 && j + 1 >= 0 && i + 1 < width && j + 1 < height) {
                if (terrain[i + 1][j + 1] != 4) {
                  if (randomizer.nextInt(waterConstant) == 0)
                    moreWater[i + 1][j + 1] = 1;
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (moreWater[i][j] == 1) {
              terrain[i][j] = 4;
      private void generateRandomMap() {
        Random randomizer = new Random();
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (randomizer.nextInt(3) == 1)
              terrain[i][j] = 0;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 1;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 3;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 2;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 2;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 1;
            else if (randomizer.nextInt(2) == 1)
              terrain[i][j] = 3;
            else
              terrain[i][j] = randomizer.nextInt(5);
        expandWater();
        for (int i = 0; i < width; i++) {
          for (int j = 0; j < height; j++) {
            if (terrain[i][j] != 0)
              landMass++;
      public int getMapHeight() {
        return height;
      public int getMapWidth() {
        return width;
      public int getSquareID(int x, int y) {
        return terrain[x][y];
      public int getSquareMovementCost(int x, int y) {
        return terrainTypes.getMovementCost(terrain[x][y]);
    }PathFinder.java:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Vector;
    public class PathFinder {
      private BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
      //The array t3D[][] represents the 2D square map where t3D.leght = map width
      //and t3D[x].lenght = map width (-1 < x < t3D.leght). The third dimension
      //is refered to the square's movement cost, witch is definite by terrain.
      //The fourth dimension will be with lenght = 3. When running the search engine
      //(expanding the explored squares) this 3 values will keep the position of
      //the previous square in 3 dimension, witch are width, height and the maximum
      //movement cost among all squares.
      private int[][][][] squares3DReference;
      //Keeps information witch squares are visited.
      private boolean[][][] visitedSquares;
      private Map map;
      //this is the queue used in the Breathed First Seatch.
      private Vector queue3D;
      //Here is saved the shortest path
      private Vector path2D;
      private int highestMovementCost;
      public PathFinder(Map aMap) {
        map = aMap;
        queue3D = new Vector();
        path2D = new Vector();
        squares3DReference = new int[map.getMapWidth()][map.getMapHeight()][][];
        visitedSquares = new boolean[map.getMapWidth()][map.getMapHeight()][];
        highestMovementCost = map.terrainTypes.getHighestMovementCost();
        buildAbstract3DTerrain();
      private void buildAbstract3DTerrain() {
        for (int x = 0; x < map.getMapWidth(); x++) {
          for (int y = 0; y <map.getMapHeight(); y++) {
            int movementCost = map.terrainTypes.getMovementCost(map.getSquareID(x, y));
            if ( movementCost > 0) {
              visitedSquares[x][y] = new boolean[highestMovementCost];
              squares3DReference[x][y] = new int[highestMovementCost][3];
              for (int z = 0; z < highestMovementCost; z++) {
                for (int t = 0; t < 3; t++) {
                  squares3DReference[x][y][z][t] = -1;
      private boolean isMoveValid(int x, int y, int z, int x2, int y2, int z2) {
        if ( x < 0 || y < 0 || z < 0 || x2 < 0 || y2 < 0 || z2 < 0 || x >= map.getMapWidth() || y >= map.getMapHeight() || z >= highestMovementCost ||  x2 >= map.getMapWidth() || y2 >= map.getMapHeight() || z2 >= highestMovementCost)
          return false;
        if (map.terrainTypes.getMovementCost(map.getSquareID(x2, y2)) < 1)
          return false;
        if (visitedSquares[x2][y2][z2])
          return false;
        if (x == x2 && y == y2)
          return true;
        else {
          if (z == map.terrainTypes.getMovementCost(map.getSquareID(x2, y2)) - 1)
            return true;
          else
            return false;
      private void clearPreviousSearchData() {
        queue3D.clear();
        path2D.clear();
        for (int x = 0; x < map.getMapWidth(); x++) {
          for (int y = 0; y < map.getMapHeight(); y++) {
            if (squares3DReference[x][y] != null) {
              for (int z = 0; z < highestMovementCost; z++) {
                visitedSquares[x][y][z] = false;
                for (int t = 0; t < 3; t++) {
                  squares3DReference[x][y][z][t] = -1;
      private Vector copyPath2D() {
        Vector path = new Vector();
        for (int i = 0; i < path2D.size(); i++) {
          path.add(path2D.get(i));
        return path;
      public Vector findPath(int sX, int sY, int gX, int gY) {
        int head = 0;
        int tail = 0;
        int x = sX;
        int y = sY;
        int z = 0;
        visitedSquares[x][y][z] = true;
        mainLoop: {
          while (tail <= head) {
            int[][] moves = getPosibleMoves(x, y, z);
            for (int i = 0; i < 9; i++) {
              if (moves[i] != null) {
                squares3DReference[moves[0]][moves[i][1]][moves[i][2]][0] = x;
    squares3DReference[moves[i][0]][moves[i][1]][moves[i][2]][1] = y;
    squares3DReference[moves[i][0]][moves[i][1]][moves[i][2]][2] = z;
    queue3D.add(moves[i]);
    if (moves[i][0] == gX && moves[i][1] == gY) {
    break mainLoop;
    visitedSquares[moves[i][0]][moves[i][1]][moves[i][2]] = true;
    head++;
    if (queue3D.size() == 0 || queue3D.size() == tail)
    break mainLoop;
    int[] nextInQueue = ((int[]) queue3D.get(tail));
    x = nextInQueue[0];
    y = nextInQueue[1];
    z = nextInQueue[2];
    tail++;
    if (squares3DReference[gX][gY][0][0] == -1) {
    clearPreviousSearchData();
    return path2D;
    fillpath2D(sX, sY, gX, gY);
    Vector path = copyPath2D();
    clearPreviousSearchData();
    return path;
    private int[][] getPosibleMoves(int x, int y, int z) {
    int[][] moves = new int[9][3];
    if (isMoveValid(x, y, z, x + 1, y, 0)) {
    moves[0][0] = x + 1;
    moves[0][1] = y;
    moves[0][2] = 0;
    else
    moves[0] = null;
    if (isMoveValid(x, y, z, x + 1, y - 1, 0)) {
    moves[1][0] = x + 1;
    moves[1][1] = y - 1;
    moves[1][2] = 0;
    else
    moves[1] = null;
    if (isMoveValid(x, y, z, x, y - 1, 0)) {
    moves[2][0] = x;
    moves[2][1] = y - 1;
    moves[2][2] = 0;
    else
    moves[2] = null;
    if (isMoveValid(x, y, z, x - 1, y - 1, 0)) {
    moves[3][0] = x - 1;
    moves[3][1] = y - 1;
    moves[3][2] = 0;
    else
    moves[3] = null;
    if (isMoveValid(x, y, z, x - 1, y, 0)) {
    moves[4][0] = x - 1;
    moves[4][1] = y;
    moves[4][2] = 0;
    else
    moves[4] = null;
    if (isMoveValid(x, y, z, x - 1, y + 1, 0)) {
    moves[5][0] = x - 1;
    moves[5][1] = y + 1;
    moves[5][2] = 0;
    else
    moves[5] = null;
    if (isMoveValid(x, y, z, x, y + 1, 0)) {
    moves[6][0] = x;
    moves[6][1] = y + 1;
    moves[6][2] = 0;
    else
    moves[6] = null;
    if (isMoveValid(x, y, z, x + 1, y + 1, 0)) {
    moves[7][0] = x + 1;
    moves[7][1] = y + 1;
    moves[7][2] = 0;
    else
    moves[7] = null;
    if (isMoveValid(x, y, z, x, y, z + 1)) {
    moves[8][0] = x;
    moves[8][1] = y;
    moves[8][2] = z + 1;
    else
    moves[8] = null;
    return moves;
    private void fillpath2D(int sX, int sY, int gX, int gY) {
    int[] gLoc = {gX, gY};
    path2D.add(gLoc);
    int x = gX;
    int y = gY;
    int z = 0;
    while (x != sX || y != sY) {
    int x2 = squares3DReference[x][y][z][0];
    int y2 = squares3DReference[x][y][z][1];
    int z2 = squares3DReference[x][y][z][2];
    x = x2;
    y = y2;
    z = z2;
    if (z == 0) {
    int[] loc = {x, y};
    path2D.insertElementAt(loc, 0);
    PathFinderTest.java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Vector;
    public class PathFinderTest {
      static BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
      static Map map;
      static int startX;
      static int startY;
      static int goalX;
      static int goalY;
      public static void main(String[] args) throws Exception {
        System.out.print("Enter map size.\nx = ");
        int width = Integer.parseInt(consoleReader.readLine());
        System.out.print("y = ");
        int height = Integer.parseInt(consoleReader.readLine());
        System.out.print("Enter strting location.\nx = ");
        startX = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("y = ");
        startY = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("Enter goal location.\nx = ");
        goalX = Integer.parseInt(consoleReader.readLine()) - 1;
        System.out.print("y = ");
        goalY = Integer.parseInt(consoleReader.readLine()) - 1;
        if (goalX < 0 || goalY < 0 || startX < 0 || startY < 0 || goalX >= width || goalY >= height || startX >= width || startY >= height) {
          System.out.println("Invalid parameters found. Program will exit");
          System.exit(0);
        map = new Map(width, height);
        map.clearGoalAndStartLocFromWater(startX, startY, goalX, goalY);
        printSolution(new Vector());
        PathFinder pathFinder = new PathFinder(map);
        long before = System.currentTimeMillis();
        Vector path = pathFinder.findPath(startX, startY, goalX, goalY);
        long after = System.currentTimeMillis();
        long time = after - before;
        printSolution(path);
        if (path.size() == 0)
          System.out.println("No path found.");
        else
          System.out.println("Path found.");
        System.out.println("Finding the path took " + time + " milliseconds");
      static void printSolution(Vector path) {
        boolean[][] pathOnMap = new boolean[map.getMapWidth()][map.getMapHeight()];
        for (int i = 0; path.size() > i; i++) {
          int[] move = (int[]) path.get(i);
          pathOnMap[move[0]][move[1]] = true;
        for (int y = 0; y < map.getMapHeight(); y++) {
          for (int x = 0; x < map.getMapWidth(); x++) {
            System.out.print(" ");
            if (pathOnMap[x][y] == false)
              System.out.print(" ");
            else
              System.out.print("0");
            if (x == startX && y == startY)
              System.out.print("S");
            else if (x == goalX && y == goalY)
              System.out.print("G");
            else
              System.out.print(map.terrainTypes.getNameFirstLetter(map.getSquareID(x, y)));
          System.out.println();
        System.out.println();
    }TerrainType.java:
    public class TerrainType {
      private int movementCost;
      private String name;
      TerrainType(int aMovementCost, String aName) {
        movementCost = aMovementCost;
        name = aName;
      public int getMovementCost() {
        return movementCost;
      public String getName() {
        return name;
      public String getNameFirstLetter() {
        return name.substring(0, 1).toUpperCase();
    }TerrainTypes.java:
    import java.util.Vector;
    public class TerrainTypes {
      //Here are saved the terrain types with the map has. ElementAt 'i' in
      //setOfTypes is represented by the number in Map.terrain[x][y] witch is
      //equal to i, were x, y are random integer as soon as they do not
      //throw ArrayIndexOutOfBoundsException. Actually this is a coding to know
      //a specific square in the map to witch terrain type is refered in setOfTypes.
      private Vector setOfTypes;
      public TerrainTypes() {
        setOfTypes = new Vector();
        setOfTypes.add(new TerrainType(1, "Plains"));
        setOfTypes.add(new TerrainType(2, "Forst"));
        setOfTypes.add(new TerrainType(3, "Jungle"));
        setOfTypes.add(new TerrainType(4, "Mountain"));
        setOfTypes.add(new TerrainType(-1, "X"));
      public int getMovementCost(int i) {
        return ((TerrainType) setOfTypes.get(i)).getMovementCost();
      public String getName(int i) {
        return ((TerrainType) setOfTypes.get(i)).getName();
      public String getNameFirstLetter(int i) {
        return ((TerrainType) setOfTypes.get(i)).getNameFirstLetter();
      public int getHighestMovementCost() {
        int max = 1;
        for (int i = 0; setOfTypes.size() > i; i++) {
          int movementCost = ((TerrainType) setOfTypes.get(i)).getMovementCost();
          if ( movementCost > 0) {
            if (max < movementCost)
              max = movementCost;
        return max;
    }I hope this program will be helpful.
    Sogartar

    Why is such a smart guy like you not using A*
    It is a general known algorithm which will find the
    optimal solution in a finite search-space (within a minimal time).
    The calculation time for the A* algorithm is influenced by two parameters:
    1 - cumulative cost
    2 - minimal expected additional cost
    The calculation of these two costs has a great influence on the
    solution.
    I think the actual problems most games experience with shortest path calculatoin are
    1 - very little time to spent calculating the shortest path
    The quickest solution might be the best for the game
    If your solution takes 1 second for the calculation of a path for one element on the board (100x100)
    What would it take for the game to calculate the path for all elements controlled by the computer ??
    If the computer controls two players which each have 50 elements to control, it would take forever...
    Don't even consider the usage of a larger board (200x200 would take 4 seconds/element when
    algorithm has complexity O(n))
    2 - low priority.
    Users tend to forgive a bad shortest path-algorithm most of the time,
    but not a bad display, bad pictures,...
    This is why most shortest-path algorithms within games were
    developed as a depth first search,
    within some earlier games this was even developed as
    a rule which went straight to the endlocation and
    takes a right/left turn when blocked by water/wall/...
    So the actual steps you should take are:
    1 - develop a normal breath-first search (to get going)
    2 - develop a normal depth-first search (to compare speed and solution with)
    3 - develop a normal dijkstra algorithm (sometimes called A)
    4 - develop a best first algorithm (called A*)
    5 - develop other AI-algorithms building upon A* (tabu-search, limited memory A*,...)
    6 - develop some other AI-algorithms (Genetic Algorithms, Simulated Annealing,...)
    7 - compare and tweak/change all search-algorithms for
    7 - a - size of maps (small versus huge)
    7 - b - optimality of the solution
    7 - c - actual usage for your game
    8 - !!! very important !!!
    Share the developed path algorithms along with remarks about speed, map-size,...
    with the rest of us. I would be very interested in such library.
    kind regards,

  • Java path error

    hi gurus
    i am facing a problem while installing SAP IDES on my desktop(windows XP) but am facing the problem in JAVA PATH settings.
    can anyobdy please tell me the step by step JAVA path settings to resolve my probem?
    thanks in advance..

    go to Run
    type - > regedit
    in u r registry
    select
    HKEY_LOCAL_MACHINE
    SOFTWARE
    JAVASOFT
    JAVARUNTIME ENVIRONMENT
    JAVA 1.4.2_12
    on the right side you will find path for Java_home
    copy the same
    go to mycomputer properties advanced environment variables create one entry
    JAVA_HOME
    <the copied text eg. C:\Program Files\Java\j2re1.4.2_13>
    now go to cmd
    type java
    it should work
    Please provide points if helpful
    Regards
    Balamurugan.P

  • Displaying Picture in a Java APPLICATION please help!!

    I have been trying to write a method that Displays a .jpg file when called. However I have not gotten far, every book I have tell you how to display pictures in an applet but not an application. I did find some code that is supposed to be for an application, but It does not compile right. Any help would be apprecidated!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PictureIt{
    public void makeImage() {
    //***Image Output Stream
    String imgFile
    = "d:\\temp\\TestImage.jpeg";
    out = new FileOutputStream(imgFile);
    BufferedImage image = null;
    image = (BufferedImage)createImage
    (panelJpeg.size.width, panelJpeg.size.height);
    Graphics g = image.getGraphics();
    panelJpeg.paintAll(g);
    }

    Displaying Picture in a Java APPLICATION please help!!
    Hope this helps.There is going to be two classes compile seperatly first class is what does the drawing
    here it is
    import javax.swing.*;
    import java.awt.*;
    public class draww extends JPanel {
    Image ball;
    int width1 = 100;
    int height1 = 100;
    public draww() {
    super();
    Toolkit kit = Toolkit.getDefaultToolkit();
    ball = kit.getImage("pic1.gif");
    public void paintComponent(Graphics comp) {
    Graphics2D comp2D = (Graphics2D) comp;
    comp2D.drawImage(ball, 20, 20, width1, height1, this);
    sound class is the container JFrame here it is
    import javax.swing.*;
    import java.awt.*;
    public class drawing extends JFrame {
    public drawing() {
    super("draw");
    setSize(400,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container pane = getContentPane();
    draww d = new draww();
    pane.add(d);
    setContentPane(pane);
    setVisible(true);
    public static void main(String[] args) {
    drawing drawing1 = new drawing();
    PS Hope this helps and see you around

  • How to get tomcat installtion path, java path n documents path in a servlet

    may someone help me get the folder and pathname for tomcat, java path and library path and also the pathname where the jsp documents are stored.
    Thanks in advance
    null

    Have a look at System.getEnv(String) and System.getProperties();
    String tomcatHome = System.getEnv("CATALINA_HOME");
    Properties props = System.getProperties();
              Enumeration<Object> keys =  props.keys();
              while(keys.hasMoreElements())
                   String key = (String) keys.nextElement();
                   String prop = System.getProperty(key);
                   System.out.println(key +" : " + prop);
              }

  • JDBC Java- mysql problem help!

    Hi, I wnat to connect to mySQL fromo Java, I followed all the instructions from the mySql web page, yet I havent been able to do it, when I compile the java progrm I keep getting class not found exceptions, I am using Fedora Core and Java was already installed-well I chose to install it when I installed the operating system, the point is that the paths are all assigned by he system not by me.
    WHat can I do?, Ive been trying over andover again with no results, hopefully somebody can help, I tried to include all the configuration in this email,
    thank you
    my java program is the following:
    t.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class t {
    public static void main (String[] args) {
    System.out.println("Hello, world!\n");
    Class.forName("com.mysql.jdbc.Driver");
    when I javac t.java
    I have the following error
    4. ERROR in t.java
    (at line 11)
    Class.forName("com.mysql.jdbc.Driver");
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    Unhandled exception type ClassNotFoundException
    when I comment out the Class.forName the hello world rogram runs fine
    when I vi /etc/java java.conf this is the result
    # System-wide Java configuration file -- sh --
    # JPackage Project [www.jpackage.org]
    # Location of jar files on the system
    JAVA_LIBDIR=/usr/share/java
    # Location of arch-specific jar files on the system
    JNI_LIBDIR=/usr/lib/java
    # Root of all JVM installations
    JVM_ROOT=/usr/lib/jvm
    # You can define a system-wide JVM root here if you're not using the default one#JAVA_HOME=$JVM_ROOT/java-gcj
    # Options to pass to the java interpreter
    JAVACMD_OPTS=
    ~
    [root@localhost test]# echo $PATH
    /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
    echo $JAVA_HOME
    it contains nothing
    ls /usr/share java*
    java
    java-1.3.0
    java-1.4.0
    java-1.4.1
    java-1.4.2
    java-1.5.0
    javadoc
    java-ext
    java-utils
    mysql-connector-java-3.1.13-bin.jar is under
    /usr/share/java
    in /etc/profile I have:
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-3.1.13-bin.jar
    in /root/.bash_profile i have
    CLASSPATH=/usr/share/java/mysql-connector-java-3.1.13-bin.jar:/usr/lib/java-ext/mysql-connector/mysql-connector-java-3.1.13-bin.jar
    export CLASSPATH
    when I echo $PATH i have
    /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin

    Thanks duff,
    The driver seems to be found
    when I run
    public class t {
    public static void main (String[] args) {
    try
    System.out.println("Hello, world!\n");
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("MySQL Driver Found");
    catch (ClassNotFoundException e)
    System.out.println("MySQL Driver NOT Found");
    e.printStackTrace();
    I feel somehow ive been focusing in the wrong side of the problem due to my ignorance in Java. Please help me to understand, the reson for which ithe runtime was telling me that there was an unhandled exception was because it is a requirement to handle all exceptions of this kind? why wouldnt it cmplain if I jst did the hello world without any exception handling, maybe because it is a requirement in the Class.forName...
    the other question is, is the message I was obtaining completely independent of the fact that the class was or was not found?
    Maybe, I should go with these questions to the newbies forum...
    thanks

  • Solution: A-Star Path Finding Algorithm (games)

    Hello everyone. I have developed several A-Star implementations for games, if you come across anyone with questions relating to path finding, please direct them to [email protected]

    I'll also be directing several rich Nigerians who need your help, too, if that is OK.

  • How to find help about javaw.exe interpreter?

    Hi,
    I hope that someone here can help me.
    I'm trying to find help about Javaw.exe command line and I wasn't able to find any document at sun.com.
    basicly I want to understand what does javaw.exe -ojvm do? but I have more questions...
    can someone direct me to an official guide at sun.com to all the command line.
    or maybe someone can explain how to find this document at sun.com
    Thanks.

    Start with the man page for java - the Java application launcher
    http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/java.html
    This reads (in part):
        The javaw command is identical to java, except that with javaw
        there is no associated console window. Use javaw when you don't
        want a command prompt window to appear. The javaw launcher will,
        however, display a dialog box with error information if a launch
        fails for some reason.I can't help you on the "-ojvm". question... there is no documentation for such a flag, and I've never heard of it.

  • I need to upgrade my version and can't find help or any other way

    I got a message saying I was using an old and insecure version of firefox. I was directed to click on help. I can't find help.
    When I clicked the free download a message said it didn't exist. Try another version.
    I have been having problems with viruses and would like to clean firefox or load a new version while keeping my homepage.
    I keep hearing firefox is known for not protecting users from viruses.

    When I try to install the free app I get three boxes that seem simple enough to follow EXCEPT the first box opens with 62% downloaded and never changes. When I try to click here it doesn't move. Once it opened the choice of open with or file . When I chose open it went to a bunch of apps that are not related. How do I select what to open it with? Why is it stuck at 62%

  • Find/search doesn't work in Finder - help!?

    I go into finder and I type in a file name to search my computer for. No matter what volume or folder I select, nothing pops up in the search window - no files, no folders, nothing. Finder just sits there. The find command doesn't seem to work. Can anyone help me fix this? I really need to find files on my computer and don't have time to sift through every folder one by one. Thanks!!!

    Hi, Todd —
    Welcome to Apple Discussions.
    I'll assume that you're talking about using Spotlight via the Finder »» Find (⌘-F) command. If I'm wrong about this, please post back to clarify the specifics.
    If nothing at all can be found, it's possible that you have inadvertently included your HD (or a significant Volume, your Documents folder, etc.) in the Privacy tab of Spotlight's preferences — which keeps it from being indexed. If the "metadata" associated with a file or folder aren't included in the indexing, they can't be searched and included in results.
    To check this, look first in System Preferences »» Spotlight »» Results — are any of the boxes checked? Only those that are will be searched. Are they in the order you'd like to see results reported? Next, look in System Preferences »» Spotlight »» Privacy. Does anything appear in this window? Anything that does will not be indexed, and thus won't be included in a search. If it is the Volume (or folders, etc.) that you want to be searched, select its name and click on to remove it.
    Spotlight will then begin to index whatever had been set as "private" — which essentially means "don't search." Note that this may take some time. The Spotlight icon at the far right side of your menu bar will show a tiny "pulsing" dot while indexing is ongoing.
    You may want to go to Finder »» Help »» Mac Help, type in "Spotlight find," and hit return. Several useful articles on this subject will appear that will help to explain this. Here is a list of corresponding Apple "Help" articles online.
    Does this help?
    Please post back to share your progress, and discuss other possibilities, as appropriate...
    Regards,
    Dean

  • Image size and mime type.. non-java guy needs help

    Image size, mime type.. non-java guy needs help
    Im not at all familiar with java so this is really weird for me to work out. I?ve been doing it all day (and half of yesterday).
    Im trying to write a custom clodFusion tag in java that gets the width, height, size and MIME types of a given file. I?ve been trying to get it to work on the command line first. I can get the width and height but cant get the size and the MIME type.
    Here is what I got
    /*import com.allaire.cfx.*;*/
    import java.awt.image.renderable.*;
    import javax.media.jai.*;
    import com.sun.media.jai.codec.*;
    import java.io.*;
    import java.util.*;
    public class ImageInfo {
    private RenderedOp image = null;
    private RenderedOp result = null;
    private int height = 0;
    private int width = 0;
    private String type = "";
    private String size = "";
    public void loadf(String file) throws IOException
    file = "80by80.jpg";
    FileSeekableStream fss = new FileSeekableStream(file);
    image = JAI.create("stream", fss);
    height = image.getHeight();
    width = image.getWidth();
    System.out.println(height + "\n");
    System.out.println(width);
    System.out.println(type);
    public static void main(String[] args) throws IOException {
    ImageInfo test = new ImageInfo();
    test.loadf(args[0]);
    can anyone please help me out to modify the above so I can also print the mime type and the file size to screen.
    thanks for any help

    any suggestions?

Maybe you are looking for

  • Automating a report generation process

    Hello guys! I just took on a new role in a company which requires me to deal with SAP BEx Analyzer. I'm completely new to this, but having gone through the report generation process, I feel the method I'm using is horribly tedious and I believe there

  • Credit memo value Is not updating in a LIS

    Hi All,        My Problem Is O am Creating a credit memo by using the billing Document Directly, with out using any return order,Return delivery. When I am seeing in the LIS Its not showing the Actual Credit memo Value for that customer its showing Z

  • Calling a mime object in the WebDynPro ABAP code dynamically

    Hi , Can anyone let me know the API to access the mime objects dynamically in the WD ABAP code. I have a text file in the WD ABAP component as a text file. I would like to pick the file with the help of API's and read the content of the file using Mi

  • Use of alternative field label in TMW

    Hi, I'm using a customer-specific field under IMG>Time Management>Time Manager's Workplace >Screen Areas>Time Data>Define Table for Time Events and I want to change the field description displayed in TMW under the Time Events tab. I've tried to use t

  • Keynote '09 will not open ppt or pptx files

    Although I have had no trouble in the past, presently I am unable to open both .ppt and .pptx PowerPoint files in Keynote. The progress bar gets about 1/4 to 1/3 across and just stays there indefinitely until I force quit Keynote (I have left my offi