Changing DFS (by adding traverse) to give a Stack implementation.

This commit is contained in:
Jonathan Turner 2024-02-06 11:38:45 -05:00
parent 156f8e0d19
commit 41c04cacec
2 changed files with 67 additions and 3 deletions

View File

@ -26,10 +26,10 @@ public class Driver {
public static void main(String[] args) { public static void main(String[] args) {
DFS solver = new DFS(); DFS solver = new DFS();
Board board = BoardGenerator.generateBoard(); Board board = BoardGenerator.generateBoard();
Board result = solver.dfs(board, 0, new ArrayList<>()); boolean result = solver.traverse(board);
int count = 0; int count = 0;
while (count != 100 || result != null) { while (count != 100 || !result) {
result = solver.dfs(board, 0, new ArrayList<>()); result = solver.traverse(board);
System.out.println(count); System.out.println(count);
count++; count++;
board = BoardGenerator.generateBoard(); board = BoardGenerator.generateBoard();

View File

@ -43,4 +43,68 @@ public class DFS {
return null; return null;
} }
public boolean traverse(Board root) {
BoardNode current = new BoardNode(root);
Stack<BoardNode> lvr = new Stack<>();
lvr.push(current);
while (!lvr.isEmpty()) {
BoardNode curr = lvr.pop();
if (curr.board.equals(solved)) {
return true;
}
List<Move> moves = curr.board.getMoves();
for (Move move : moves) {
Board child = new Board(curr.board);
child.swap(move);
if (!curr.hasAncestor(child)) {
BoardNode childNode = new BoardNode(child, curr);
curr.addChild(childNode);
lvr.add(childNode);
}
}
}
return false;
}
}
class BoardNode {
public Board board;
public BoardNode parent;
public List<BoardNode> children;
public BoardNode(Board child, BoardNode parent) {
this.board = child;
this.parent = parent;
this.children = new ArrayList<>();
}
public BoardNode (Board child) {
this.board = child;
this.parent = null;
this.children = new ArrayList<>();
}
public boolean hasAncestor(Board board) {
BoardNode current = this;
while (current.parent != null) {
current = current.parent;
if (current.board.equals(board)) {
return true;
}
}
return false;
}
public void addChild(BoardNode child) {
if (child != null) {
children.add(child);
}
}
} }