Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. int[][] maze = new int[width][height]; // The maze
  2. boolean[][] wasHere = new boolean[width][height];
  3. boolean[][] correctPath = new boolean[width][height]; // The solution to the maze
  4. int startX, startY; // Starting X and Y values of maze
  5. int endX, endY;     // Ending X and Y values of maze
  6.  
  7. public void solveMaze() {
  8.     maze = generateMaze(); // Create Maze (1 = path, 2 = wall)
  9.     for (int row = 0; row < maze.length; row++)  
  10.         // Sets boolean Arrays to default values
  11.         for (int col = 0; col < maze[row].length; col++){
  12.             wasHere[row][col] = false;
  13.             correctPath[row][col] = false;
  14.         }
  15.     boolean b = recursiveSolve(startX, startY);
  16.     // Will leave you with a boolean array (correctPath)
  17.     // with the path indicated by true values.
  18.     // If b is false, there is no solution to the maze
  19. }
  20. public boolean recursiveSolve(int x, int y) {
  21.     if (x == endX && y == endY) return true; // If you reached the end
  22.     if (maze[x][y] == 2 || wasHere[x][y]) return false;  
  23.     // If you are on a wall or already were here
  24.     wasHere[x][y] = true;
  25.     if (x != 0) // Checks if not on left edge
  26.         if (recursiveSolve(x-1, y)) { // Recalls method one to the left
  27.             correctPath[x][y] = true; // Sets that path value to true;
  28.             return true;
  29.         }
  30.     if (x != width - 1) // Checks if not on right edge
  31.         if (recursiveSolve(x+1, y)) { // Recalls method one to the right
  32.             correctPath[x][y] = true;
  33.             return true;
  34.         }
  35.     if (y != 0)  // Checks if not on top edge
  36.         if (recursiveSolve(x, y-1)) { // Recalls method one up
  37.             correctPath[x][y] = true;
  38.             return true;
  39.         }
  40.     if (y != height- 1) // Checks if not on bottom edge
  41.         if (recursiveSolve(x, y+1)) { // Recalls method one down
  42.             correctPath[x][y] = true;
  43.             return true;
  44.         }
  45.     return false;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement