-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRatInDeadMazeFourDirection
More file actions
68 lines (59 loc) · 2.57 KB
/
RatInDeadMazeFourDirection
File metadata and controls
68 lines (59 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* 🐭 RatInDeadMazeFourDirection.java
*
* This program finds all possible paths 🛣️ from the top-left to the bottom-right corner
* of a maze using recursion 🔁 and backtracking 🔙. The rat 🐭 can move in four directions:
* right ➡️ (R), down ⬇️ (D), left ⬅️ (L), and up ⬆️ (U). Cells with value 0 are blocked 🚫.
*
* Author: Adam Warlord
* GitHub: https://github.com/Warlord27/
*/
public class RatInDeadMazeAnyGrid {
public static void main(String[] args) {
// Define the grid (can be any size or shape)
int[][] maze = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 1, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 1, 1, 1, 1 },
{ 1, 0, 1, 0, 1 }
};
int row = maze.length; // Number of rows
int col = maze[0].length; // Number of columns
// Visited array to track visited cells
boolean[][] isVisited = new boolean[row][col];
System.out.println("🧭 All possible paths from start to end:");
printPaths(0, 0, row - 1, col - 1, "", maze, isVisited);
}
/**
* 🔁 Recursively explores all paths from (sr, sc) to (er, ec).
*
* @param sr current row 📍
* @param sc current column 📍
* @param er end row 🏁
* @param ec end column 🏁
* @param path current path as a string of directions 🧵
* @param maze the maze grid (1: open ✅, 0: blocked 🚫)
* @param isVisited grid to track visited positions 👣
*/
static void printPaths(int sr, int sc, int er, int ec, String path, int[][] maze, boolean[][] isVisited) {
// 🛑 Base case: out of bounds or blocked/visited
if (sr < 0 || sc < 0 || sr >= maze.length || sc >= maze[0].length || maze[sr][sc] == 0 || isVisited[sr][sc]) {
return;
}
// ✅ If destination is reached, print the path
if (sr == er && sc == ec) {
System.out.println("✅ Path found: " + path);
return;
}
// 🚩 Mark current cell as visited
isVisited[sr][sc] = true;
// ➡️ Explore in all four directions
printPaths(sr, sc + 1, er, ec, path + "R", maze, isVisited); // Right ➡️
printPaths(sr + 1, sc, er, ec, path + "D", maze, isVisited); // Down ⬇️
printPaths(sr, sc - 1, er, ec, path + "L", maze, isVisited); // Left ⬅️
printPaths(sr - 1, sc, er, ec, path + "U", maze, isVisited); // Up ⬆️
// 🔙 Backtrack: unmark the current cell
isVisited[sr][sc] = false;
}
}