|
| 1 | +package com.thealgorithms.backtracking; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Rat in a Maze Problem using Backtracking. |
| 8 | + * |
| 9 | + * <p>Given an {@code n x n} binary maze where {@code 1} represents an open cell |
| 10 | + * and {@code 0} represents a blocked cell, find all paths for a rat starting at |
| 11 | + * the top-left cell {@code (0, 0)} to reach the bottom-right cell {@code (n-1, n-1)}. |
| 12 | + * |
| 13 | + * <p>The rat can move in four directions: Up (U), Down (D), Left (L), Right (R). |
| 14 | + * Each cell may be visited at most once per path. |
| 15 | + * |
| 16 | + * <p>Time Complexity: O(4^(n²)) in the worst case (four choices per cell). |
| 17 | + * Space Complexity: O(n²) for the visited matrix and recursion stack. |
| 18 | + * |
| 19 | + * <p>Example: |
| 20 | + * <pre> |
| 21 | + * maze = { {1, 0, 0, 0}, |
| 22 | + * {1, 1, 0, 1}, |
| 23 | + * {0, 1, 0, 0}, |
| 24 | + * {0, 1, 1, 1} } |
| 25 | + * Output: ["DDRDRR", "DRDDRR"] (two valid paths) |
| 26 | + * </pre> |
| 27 | + * |
| 28 | + * @see <a href="https://en.wikipedia.org/wiki/Maze_solving_algorithm">Maze solving algorithm</a> |
| 29 | + * @author the-Sunny-Sharma (<a href="https://github.com/the-Sunny-Sharma">GitHub</a>) |
| 30 | + */ |
| 31 | +public final class RatInAMaze { |
| 32 | + |
| 33 | + private RatInAMaze() { |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Finds all paths from the top-left to the bottom-right of the given maze. |
| 38 | + * |
| 39 | + * @param maze an {@code n x n} binary matrix where {@code 1} = open, {@code 0} = blocked |
| 40 | + * @return a sorted list of all valid path strings using directions D, L, R, U; |
| 41 | + * an empty list if no path exists |
| 42 | + * @throws IllegalArgumentException if the maze is null, empty, or not square |
| 43 | + */ |
| 44 | + public static List<String> findPaths(final int[][] maze) { |
| 45 | + if (maze == null || maze.length == 0) { |
| 46 | + throw new IllegalArgumentException("Maze must not be null or empty."); |
| 47 | + } |
| 48 | + int n = maze.length; |
| 49 | + for (int[] row : maze) { |
| 50 | + if (row.length != n) { |
| 51 | + throw new IllegalArgumentException("Maze must be a square (n x n) matrix."); |
| 52 | + } |
| 53 | + } |
| 54 | + List<String> results = new ArrayList<>(); |
| 55 | + if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) { |
| 56 | + return results; |
| 57 | + } |
| 58 | + boolean[][] visited = new boolean[n][n]; |
| 59 | + solve(maze, 0, 0, n, "", visited, results); |
| 60 | + return results; |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Recursive backtracking helper that explores all four directions. |
| 65 | + * |
| 66 | + * @param maze the binary maze |
| 67 | + * @param row current row position |
| 68 | + * @param col current column position |
| 69 | + * @param n maze dimension |
| 70 | + * @param path path string built so far |
| 71 | + * @param visited tracks visited cells for the current path |
| 72 | + * @param results accumulates complete paths |
| 73 | + */ |
| 74 | + private static void solve(final int[][] maze, final int row, final int col, final int n, final String path, final boolean[][] visited, final List<String> results) { |
| 75 | + // Base case: reached destination |
| 76 | + if (row == n - 1 && col == n - 1) { |
| 77 | + results.add(path); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + // Mark current cell as visited |
| 82 | + visited[row][col] = true; |
| 83 | + |
| 84 | + // Explore in alphabetical order: Down, Left, Right, Up |
| 85 | + // Down |
| 86 | + if (isSafe(maze, row + 1, col, n, visited)) { |
| 87 | + solve(maze, row + 1, col, n, path + 'D', visited, results); |
| 88 | + } |
| 89 | + // Left |
| 90 | + if (isSafe(maze, row, col - 1, n, visited)) { |
| 91 | + solve(maze, row, col - 1, n, path + 'L', visited, results); |
| 92 | + } |
| 93 | + // Right |
| 94 | + if (isSafe(maze, row, col + 1, n, visited)) { |
| 95 | + solve(maze, row, col + 1, n, path + 'R', visited, results); |
| 96 | + } |
| 97 | + // Up |
| 98 | + if (isSafe(maze, row - 1, col, n, visited)) { |
| 99 | + solve(maze, row - 1, col, n, path + 'U', visited, results); |
| 100 | + } |
| 101 | + |
| 102 | + // Backtrack: unmark current cell |
| 103 | + visited[row][col] = false; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Checks whether moving to {@code (row, col)} is valid. |
| 108 | + * |
| 109 | + * @param maze the binary maze |
| 110 | + * @param row target row |
| 111 | + * @param col target column |
| 112 | + * @param n maze dimension |
| 113 | + * @param visited tracks visited cells for the current path |
| 114 | + * @return {@code true} if the cell is within bounds, open, and not yet visited |
| 115 | + */ |
| 116 | + private static boolean isSafe(final int[][] maze, final int row, final int col, final int n, final boolean[][] visited) { |
| 117 | + return row >= 0 && row < n && col >= 0 && col < n && maze[row][col] == 1 && !visited[row][col]; |
| 118 | + } |
| 119 | +} |
0 commit comments