Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DFS {
- // Solves given maze recursively, input starting position in maze.
- public static boolean solve(int[][] maze, int x, int y) {
- // 3 is the cell the algorithm is supposed to find.
- if (maze[x][y] == 3) {
- maze[x][y] = 2;
- return true;
- }
- int orig = maze[x][y];
- maze[x][y] = 2;
- // Looks up.
- if (x > 0 && (maze[x-1][y] == 0 || maze[x-1][y] == 3) && solve (maze, x-1, y) ) {
- return true;
- }
- // Looks down
- if (x < maze.length && (maze[x+1][y] == 0 || maze[x+1][y] == 3) && solve (maze, x+1, y) ) {
- return true;
- }
- // Looks right.
- if (y < maze.length+1 && (maze[x][y+1] == 0 || maze[x][y+1] == 0) && solve (maze, x, y+1) ) {
- return true;
- }
- // Looks left.
- if (y > 0 && (maze[x][y-1] == 0 || maze[x][y+1] == 3) && solve (maze, x, y-1) ) {
- return true;
- }
- maze[x][y] = orig;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement