1 package puzzle.solver;
2
3 import puzzle.state.PuzzleState;
4
5 import java.util.Deque;
6 import java.util.HashSet;
7 import java.util.LinkedList;
8 import java.util.Optional;
9
10 public class BreadthFirstSearch {
11
12 public Optional<Node> search(PuzzleState state) {
13 Deque<Node> open = new LinkedList<Node>();
14 var seen = new HashSet<Node>();
15 var start = new Node(state);
16 open.add(start);
17 seen.add(start);
18 while (! open.isEmpty()) {
19 var selected = open.pollFirst();
20 if (selected.getState().isGoal()) {
21 return Optional.of(selected);
22 }
23 while (selected.hasNextChild()) {
24 var nextChild = selected.nextChild().get();
25 if (! seen.contains(nextChild)) {
26 open.offerLast(nextChild);
27 seen.add(nextChild);
28 }
29 }
30 }
31 return Optional.empty();
32 }
33
34 public void printPathTo(Node node) {
35 node.getParent().ifPresent(this::printPathTo);
36 System.out.println(node);
37 }
38
39 public static void main(String[] args) {
40 var bfs = new BreadthFirstSearch();
41 var result = bfs.search(new PuzzleState());
42 result.ifPresentOrElse(
43 bfs::printPathTo,
44 () -> System.out.println("No solution found")
45 );
46 }
47
48 }