Rat In A Maze Problem - Solution in Java [Recursion and Backtracking]

 Problem - Rat In A Maze

Algorithm - Recursion and Backtracking

Programming Language - Java


import java.util.Arrays;

class Main {

    static int[][] maze = {
            {1, 1, 0, 1},
            {1, 1, 1, 1},
            {0, 1, 0, 0},
            {0, 1, 1, 1}
    };

    static int[][] path = {
            {0, 0, 0, 0},
            {0, 0, 0, 0},
            {0, 0, 0, 0},
            {0, 0, 0, 0}
    };

    public static void main(String[] args) {
        move(0, 0);
        for (int[] i : path) {
            System.out.println(Arrays.toString(i));
        }
    }

    public static boolean move(int x, int y) {
        /* End of the maze? */
        if (x == (maze.length - 1) && y == (maze.length-1)) {
            path[x][y] = 1;
            return true;
        }

        if (isValidPath(x, y)) {
            path[x][y] = 1;
            /* x-direction */
            if (move(x + 1, y)) return true;

            /* y-direction */
            if (move(x, y + 1)) return true;

            /* backtracking */
            path[x][y] = 0;
        }
        return false;
    }

    public static boolean isValidPath(int x, int y) {
        return x != maze.length && y != maze.length && maze[x][y] == 1;
    }
}

Comments

Popular posts from this blog

N-Queen Arrangement Problem [Backtracking]

Clone Graph Problem : Recursive Approach - Java