-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackTracking.java
46 lines (37 loc) · 1.14 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
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);
}
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;
}
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;
}
}