-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFSGenerator.java
75 lines (50 loc) · 2.48 KB
/
BFSGenerator.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
import java.util.ArrayDeque;
public class BFSGenerator implements MazeGenerator{
public void generate(Maze m){
// boolean for knowing if the maze is solvable
boolean solvable = false;
while(!solvable){
ArrayDeque<Square> bfsQueue = new ArrayDeque<Square>();
// generate new random maze
m.genRandMaze();
// start and end squares
Square start = m.maze[0][0];
Square end = m.maze[m.getRows()-1][m.getColumns()-1];
// add start to the queue
bfsQueue.addFirst(start);
start.squareVisited = true;
while(bfsQueue.size() > 0){
// add neighbor variable for the next square to examine
Square currentSquare = bfsQueue.peekFirst();
// add the neighbors of the square in the head of the queue that don't have walls and the square hasnt been visited
if(!currentSquare.n && currentSquare.locationY-1 >= 0 && !m.maze[currentSquare.locationY-1][currentSquare.locationX].squareVisited){
//System.out.println("Adding North Square");
bfsQueue.addLast(m.maze[currentSquare.locationY-1][currentSquare.locationX]);
m.maze[currentSquare.locationY-1][currentSquare.locationX].squareVisited = true;
}
if(!currentSquare.e && currentSquare.locationX+1 <= m.getColumns()-1 && !m.maze[currentSquare.locationY][currentSquare.locationX+1].squareVisited){
//System.out.println("Adding East Square");
m.maze[currentSquare.locationY][currentSquare.locationX+1].squareVisited = true;
bfsQueue.addLast(m.maze[currentSquare.locationY][currentSquare.locationX+1]);
}
if(!currentSquare.w && currentSquare.locationX-1 >= 0 && !m.maze[currentSquare.locationY][currentSquare.locationX-1].squareVisited){
// System.out.println("Adding West Square");
m.maze[currentSquare.locationY][currentSquare.locationX-1].squareVisited = true;
bfsQueue.addLast(m.maze[currentSquare.locationY][currentSquare.locationX-1]);
}
if(!currentSquare.s && currentSquare.locationY+1 <= m.getRows()-1 && !m.maze[currentSquare.locationY+1][currentSquare.locationX].squareVisited){
// System.out.println("Adding South Square");
m.maze[currentSquare.locationY+1][currentSquare.locationX].squareVisited = true;
bfsQueue.addLast(m.maze[currentSquare.locationY+1][currentSquare.locationX]);
}
if(currentSquare == end){
solvable = true; // maze has a solution
//System.out.println("Solved");
break;
}
// remove the current square
bfsQueue.pollFirst();
}
}
}
}