Skip to main content

Command Palette

Search for a command to run...

rat in maze

Published
2 min readView as Markdown
import java.util.*;

class Solution {
    // List to store all possible paths
    private ArrayList<String> ans;
    // Recursive helper function to explore the maze
    private void helper(int[][] mat, int i, int j, int n, int m, String path) {
        // Check for out-of-bound or blocked cell
        if (i < 0 || j < 0 || i >= n || j >= m || mat[i][j] != 1) {
            return;
        }
        // If destination is reached, add the path to the answer
        if (i == n - 1 && j == m - 1) {
            ans.add(path);
            return;
        }
        // Mark the cell as visited
        mat[i][j] = -1;
        // Explore all four directions
        helper(mat, i - 1, j, n, m, path + "U"); // Up
        helper(mat, i + 1, j, n, m, path + "D"); // Down
        helper(mat, i, j - 1, n, m, path + "L"); // Left
        helper(mat, i, j + 1, n, m, path + "R"); // Right

        // Backtrack: Unmark the cell
        mat[i][j] = 1;
    }
    // Main function to be called with the maze input
    public ArrayList<String> ratInMaze(int[][] maze) {
        ans = new ArrayList<>();
        int n = maze.length;
        int m = maze[0].length;

        // Start only if the starting cell is not blocked
        if (maze[0][0] == 1) {
            helper(maze, 0, 0, n, m, "");
        }
        // Sort the paths lexicographically
        Collections.sort(ans);
        return ans;
    }
}

More from this blog

Amit singh's blog

235 posts