-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecursiveBacktracking.java
122 lines (110 loc) · 3.28 KB
/
RecursiveBacktracking.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import java.util.*;
public class RecursiveBacktracking {
Stack<Node> stack = new Stack<>();
int w;
int h;
int numVisited;
/*
2d-array of Nodes for storing the maze
*/
Node[][] maze;
public RecursiveBacktracking(int w, int h){
this.w = w;
this.h = h;
maze = new Node[w][h];
/*
Fill the maze with nodes
*/
for(int i = 0; i < w; i++){
for(int j = 0; j < h; j++){
maze[i][j] = new Node(i, j);
}
}
/*
Start position (0, 0)
*/
stack.push(maze[0][0]);
maze[0][0].setVisited();
numVisited = 1;
}
public void genMaze() {
Random rand = new Random();
while(numVisited < w*h){
int x = stack.peek().x;
int y = stack.peek().y;
// Create list of unvisited neighbours
ArrayList<Node> neighbours = new ArrayList<>();
//Look North
if(y > 0) {
if (!(maze[x][y-1].isVisited())) {
neighbours.add(maze[x][y-1]);
}
}
// Look East
if(x < w-1) {
if (!(maze[x+1][y].isVisited())) {
neighbours.add(maze[x+1][y]);
}
}
// Look South
if(y < h-1) {
if (!(maze[x][y+1].isVisited())) {
neighbours.add(maze[x][y+1]);
}
}
// Look West
if(x > 0) {
if (!(maze[x-1][y].isVisited())) {
neighbours.add(maze[x-1][y]);
}
}
if(!neighbours.isEmpty()){
//Random neighbour
Node next = neighbours.get(rand.nextInt(neighbours.size()));
/*
Set path between neighbour and current node
*/
//Passage North
if(y > next.y){
maze[x][y].addPassage(1);
maze[next.x][next.y].addPassage(4);
}
//Passage East
if(x > next.x){
maze[x][y].addPassage(8);
maze[next.x][next.y].addPassage(2);
}
//Passage South
if(y < next.y){
maze[x][y].addPassage(4);
maze[next.x][next.y].addPassage(1);
}
//Passage West
if(x < next.x){
maze[x][y].addPassage(2);
maze[next.x][next.y].addPassage(8);
}
// New position
stack.push(next);
maze[next.x][next.y].setVisited();
numVisited++;
/*
If we do not have any unvisited neighbours, backtrack.
*/
} else {
stack.pop();
}
}
}
public void graphMaze() {
DrawMaze dm = new DrawMaze(w, h, maze);
dm.showMaze();
}
public static void main(String[] args) {
int width = 20;
int height = 20;
RecursiveBacktracking rb = new RecursiveBacktracking(width, height);
rb.genMaze();
rb.graphMaze();
}
}