-
Notifications
You must be signed in to change notification settings - Fork 7
/
AllPaths.java
91 lines (72 loc) · 2.47 KB
/
AllPaths.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package backtracking;
import java.util.Arrays;
public class AllPaths {
public static void main(String[] args) {
boolean[][] board = {
{true, true, true},
{true, true, true},
{true, true, true}
};
int[][] path = new int[board.length][board[0].length];
allPathPrint("", board, 0, 0, path, 1);
}
static void allPath(String p, boolean[][] maze, int r, int c) {
if (r == maze.length - 1 && c == maze[0].length - 1) {
System.out.println(p);
return;
}
if (!maze[r][c]) {
return;
}
// i am considering this block in my path
maze[r][c] = false;
if (r < maze.length - 1) {
allPath(p + 'D', maze, r+1, c);
}
if (c < maze[0].length - 1) {
allPath(p + 'R', maze, r, c+1);
}
if (r > 0) {
allPath(p + 'U', maze, r-1, c);
}
if (c > 0) {
allPath(p + 'L', maze, r, c-1);
}
// this line is where the function will be over
// so before the function gets removed, also remove the changes that were made by that function
maze[r][c] = true;
}
static void allPathPrint(String p, boolean[][] maze, int r, int c, int[][] path, int step) {
if (r == maze.length - 1 && c == maze[0].length - 1) {
path[r][c] = step;
for(int[] arr : path) {
System.out.println(Arrays.toString(arr));
}
System.out.println(p);
System.out.println();
return;
}
if (!maze[r][c]) {
return;
}
// i am considering this block in my path
maze[r][c] = false;
path[r][c] = step;
if (r < maze.length - 1) {
allPathPrint(p + 'D', maze, r+1, c, path, step+1);
}
if (c < maze[0].length - 1) {
allPathPrint(p + 'R', maze, r, c+1, path, step+1);
}
if (r > 0) {
allPathPrint(p + 'U', maze, r-1, c, path, step+1);
}
if (c > 0) {
allPathPrint(p + 'L', maze, r, c-1, path, step+1);
}
// this line is where the function will be over
// so before the function gets removed, also remove the changes that were made by that function
maze[r][c] = true;
path[r][c] = 0;
}
}