Advertisement
Guest User

Maze Solver DFS(?)

a guest
Jan 3rd, 2021
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. public class DFS {
  2.    
  3.     // Solves given maze recursively, input starting position in maze.
  4.     public static boolean solve(int[][] maze, int x, int y) {
  5.        
  6.        
  7.         // 3 is the cell the algorithm is supposed to find.
  8.         if (maze[x][y] == 3) {
  9.             maze[x][y] = 2;
  10.             return true;
  11.         }
  12.        
  13.         int orig = maze[x][y];
  14.         maze[x][y] = 2;
  15.        
  16.         // Looks up.
  17.         if (x > 0 && (maze[x-1][y] == 0 || maze[x-1][y] == 3)  && solve (maze, x-1, y) ) {
  18.             return true;
  19.         }
  20.         // Looks down
  21.         if (x < maze.length && (maze[x+1][y] == 0 || maze[x+1][y] == 3)  && solve (maze, x+1, y) ) {
  22.             return true;
  23.         }
  24.         // Looks right.
  25.         if (y < maze.length+1 && (maze[x][y+1] == 0 || maze[x][y+1] == 0)  && solve (maze, x, y+1) ) {
  26.             return true;
  27.         }
  28.         // Looks left.
  29.         if (y > 0 && (maze[x][y-1] == 0 || maze[x][y+1] == 3)  && solve (maze, x, y-1) ) {
  30.             return true;
  31.         }
  32.        
  33.         maze[x][y] = orig;
  34.        
  35.         return false;
  36.     }
  37.    
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement