Depth-First - Find shortest route in grid


SUBMITTED BY: Guest

DATE: Nov. 24, 2014, 7:27 p.m.

FORMAT: Java

SIZE: 3.0 kB

HITS: 1048

  1. import java.util.*;
  2. public class Main {
  3. public static final int FLOOR = 0;
  4. public static final int WALL = 1;
  5. public static final int START = 2;
  6. public static final int GOAL = 3;
  7. public static int shortestRoute(int[][] map) {
  8. int startX = -1;
  9. int startY = -1;
  10. int goalX = -1;
  11. int goalY = -1;
  12. int width = map.length;
  13. int height = map[0].length;
  14. int[][] trip = new int[width][height];
  15. // Find start and goal
  16. for (int x=0; x < width; x++) {
  17. for (int y=0; y < height; y++) {
  18. map[x][y] = 0;
  19. if (map[x][y] == START) {
  20. startX = x;
  21. startY = y;
  22. } else if (map[x][y] == GOAL) {
  23. goalX = x;
  24. goalY = y;
  25. }
  26. }
  27. }
  28. ArrayDeque<Point> queue = new ArrayDeque<Point>();
  29. queue.push(new Point(startX, startY));
  30. map[startX][startY] = WALL;
  31. while (queue.size() > 0) {
  32. Point point = queue.pollLast();
  33. int x = point.x;
  34. int y = point.y;
  35. // Go through all four directions
  36. for (int i=0; i < 4; i++) {
  37. int dx = x;
  38. int dy = y;
  39. switch (i) {
  40. case 0:
  41. dy++;
  42. break;
  43. case 1:
  44. dx++;
  45. break;
  46. case 2:
  47. dy--;
  48. break;
  49. case 3:
  50. dx--;
  51. break;
  52. }
  53. if (dx < 0 || dx > width-1 || dy < 0 || dy > height-1) {
  54. continue;
  55. }
  56. if (map[dx][dy] == WALL) {
  57. continue;
  58. }
  59. queue.push(new Point(dx, dy));
  60. map[dx][dy] = WALL;
  61. trip[dx][dy] = trip[x][y]+1;
  62. }
  63. }
  64. if (map[goalX][goalY] == GOAL) {
  65. return -1;
  66. } else {
  67. return trip[goalX][goalY];
  68. }
  69. }
  70. public static void main(String[] args) {
  71. int[][] map = {{1,1,1,1,1,1,1,1},
  72. {1,0,3,1,0,0,0,1},
  73. {1,0,1,1,0,1,0,1},
  74. {1,0,0,0,0,2,0,1},
  75. {1,1,1,1,1,1,1,1}};
  76. System.out.println(shortestRoute(map));
  77. }
  78. }

comments powered by Disqus