-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackTracking.java
85 lines (73 loc) · 2.4 KB
/
BackTracking.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
import java.util.Arrays;
public class BackTracking {
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];
// allPath("",board,0,0);
allPathPrint("",board,0,0,path,1);
}
static void allPath(String p,boolean[][] maze, int r,int c){
// here takes it goes all the 4 directions
if (r == maze.length-1 && c == maze[0].length-1){
System.out.println(p);
return;
}
if (!maze[r][c]){
return;
}
maze[r][c] = false;
if (r < maze.length-1){
allPath(p + 'D',maze,r+1,c);
}
if (c < maze.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 calls
maze[r][c] = true;
}
static void allPathPrint(String p,boolean[][] maze, int r,int c,int[][] path,int step){
// here takes it goes all the 4 directions
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;
}
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.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 calls
maze[r][c] = true;
}
}