Skip to content

Instantly share code, notes, and snippets.

@ignaciomosca
Created November 25, 2019 22:20
Show Gist options
  • Save ignaciomosca/c8cde3ee960930882106322417d99ec0 to your computer and use it in GitHub Desktop.
Save ignaciomosca/c8cde3ee960930882106322417d99ec0 to your computer and use it in GitHub Desktop.
/***
* @param board ChessBoard
* @param pieces Chess Pieces selected by the user
* @param solutions valid solutions to the problem
* @param testedConfigurations Board configurations to which solutions were not found
* @return return a list of possible solutions to the problem in the form of a list of filled chess boards
*/
public static Set<Board> solution(Board board, List<Character> pieces, Set<Board> solutions, Set<Board> testedConfigurations) {
if (!pieces.isEmpty()) { // if pieces is empty I return the solutions
for (int i = 1; i < board.getM(); i++) {
for (int j = 1; j < board.getN(); j++) {
// I iterate over the dimensions of the board, create a new piece, try to place it on
// the board. If it's safe I add it to the used pieces and recursively call
// the solution method. I have an auxiliary collection, so I don't try board configurations twice
ChessPiece c = PieceFactory.createPiece(pieces.get(0), i, j);
if (board.isSafe(c)) {
Board b = board.place(c);
if (pieces.size() != 1) {
if (testedConfigurations.add(b)) {
solution(b, ImmutableUtils.removeFirstPiece(pieces), solutions, testedConfigurations);
}
} else {
solutions.add(b);
}
}
}
}
}
return solutions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment