-
Notifications
You must be signed in to change notification settings - Fork 0
/
SolveMazeBFS2.java
105 lines (91 loc) · 2.58 KB
/
SolveMazeBFS2.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
import java.io.File;
import java.util.Scanner;
public class SolveMazeBFS2 {
private static int[][] array;
private static AdvCSQueue<Cell> queue = new AdvCSQueue<Cell>();
public static void main(String[] args) throws Exception {
SolveMazeDFS.readMaze();
SolveMazeDFS.printMaze(array);
solveMaze();
// Reverses queue returned by solveMaze();
AdvCSQueue<Cell> reverse = new AdvCSQueue<Cell>();
while (!(queue.isEmpty()))
{
reverse.enqueue(queue.dequeue());
}
// Prints queue
while (!(reverse.isEmpty()))
{
System.out.print("(" + reverse.peek().row);
System.out.print("," + reverse.peek().col + ")");
System.out.print(" ");
reverse.dequeue();
}
}
static class Cell {
int row, col;
Cell cell;
public Cell(int row_, int col_, Cell cell_)
{
row = row_;
col = col_;
cell = cell_;
}
}
public static AdvCSQueue solveMaze()
{
// enqueues the initial position of 0,0 to the queue
queue.enqueue(new Cell(0,0, null));
Cell cur = new Cell(0,0, null);
while(array[queue.peek().row][queue.peek().col] != 2 && (!queue.isEmpty()))
{
placeVisits(queue.peek().row, queue.peek().col);
cur = new Cell(queue.peek().row, queue.peek().col, cur);
if (queue.peek().row + 1 < array.length && ifPossible(queue.peek().row + 1, queue.peek().col))
{
queue.enqueue(new Cell(queue.peek().row + 1, queue.peek().col, cur));
}
if (queue.peek().row - 1 >= 0 && ifPossible(queue.peek().row - 1, queue.peek().col))
{
queue.enqueue(new Cell(queue.peek().row - 1, queue.peek().col, cur));
}
if (queue.peek().col + 1 < array[0].length && ifPossible(queue.peek().row, queue.peek().col + 1))
{
queue.enqueue(new Cell(queue.peek().row, queue.peek().col + 1, cur));
}
if (queue.peek().col - 1 >= 0 && ifPossible(queue.peek().row, queue.peek().col - 1))
{
queue.enqueue(new Cell(queue.peek().row, queue.peek().col - 1, cur));
}
else
{
queue.dequeue();
}
}
// Prints out the solved array
for (int r = 0; r < array.length; r++)
{
System.out.println();
for(int c = 0; c < array[0].length; c++)
{
System.out.print(array[r][c]);
}
}
System.out.println();
return queue;
}
// Checks to see, based off the maze's rules, whether or not the object can
// move to a position.
public static boolean ifPossible(int row, int col)
{
if (array[row][col] == 1 || array[row][col] == 2)
return true;
else
return false;
}
// A method to replace the current position with a 7 to show it was visited.
public static void placeVisits(int row, int col)
{
array[row][col] = 7;
}
}