-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMazePaths.java
58 lines (46 loc) · 1.67 KB
/
MazePaths.java
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
import java.util.ArrayList;
public class MazePaths {
static String direction = "DLRU";
static int[] dr = { 1, 0, 0, -1 };
static int[] dc = { 0, -1, 1, 0 };
static boolean isValid(int row, int col, int n, int[][] maze) {
return row >= 0 && col >= 0 && row < n && col < n && maze[row][col] == 1;
}
static void findPath(int row, int col, int[][] maze, int n, ArrayList<String> ans, StringBuilder currentPath) {
if (row == n - 1 && col == n - 1) {
ans.add(currentPath.toString());
return;
}
maze[row][col] = 0;
for (int i = 0; i < 4; i++) {
int nextrow = row + dr[i];
int nextcol = col + dc[i];
if (isValid(nextrow, nextcol, n, maze)) {
currentPath.append(direction.charAt(i));
findPath(nextrow, nextcol, maze, n, ans, currentPath);
currentPath.deleteCharAt(currentPath.length() - 1);
}
}
maze[row][col] = 1;
}
public static void main(String[] args) {
int[][] maze = { { 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 1, 1, 0, 0 },
{ 0, 1, 1, 1 } };
int n = maze.length;
ArrayList<String> result = new ArrayList<>();
StringBuilder currentPath = new StringBuilder();
if (maze[0][0] != 0 && maze[n - 1][n - 1] != 0) {
findPath(0, 0, maze, n, result, currentPath);
}
if (result.isEmpty()) {
System.out.println(-1);
} else {
for (String path : result) {
System.out.print(path + " ");
}
System.out.println();
}
}
}