-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMazeSolver.java
More file actions
57 lines (45 loc) · 1.7 KB
/
MazeSolver.java
File metadata and controls
57 lines (45 loc) · 1.7 KB
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
import java.util.*;
public class MazeSolver {
private Maze maze;
public MazeSolver(Maze maze) {
this.maze = maze;
}
public List<Cell> solveDFS() {
Set<Cell> seenCells = new HashSet<>();
Map<Cell, Cell> cameFrom = new HashMap<>();
Stack<Cell> cellStack = new Stack<>();
// start walking from the entrance and aim for the exit
Cell startCell = maze.getStart();
Cell endCell = maze.getEnd();
cellStack.push(startCell);
seenCells.add(startCell);
while (!cellStack.isEmpty()) {
Cell currentCell = cellStack.pop();
// stop early once we hit the goal
if (currentCell.equals(endCell)) {
return reconstructPath(cameFrom, startCell, endCell);
}
// explore every open neighbor we have not seen yet
for (Cell nextCell : maze.getNeighbors(currentCell)) {
if (!seenCells.contains(nextCell)) {
seenCells.add(nextCell);
cameFrom.put(nextCell, currentCell);
cellStack.push(nextCell);
}
}
}
// no path found
return new ArrayList<>();
}
private List<Cell> reconstructPath(Map<Cell, Cell> cameFrom, Cell startCell, Cell endCell) {
List<Cell> path = new ArrayList<>();
Cell walker = endCell;
while (walker != null && !walker.equals(startCell)) {
path.add(walker);
walker = cameFrom.get(walker);
}
path.add(startCell);
Collections.reverse(path);
return path;
}
}