FourQueens
unknown
java
3 years ago
1.6 kB
6
Indexable
import java.util.ArrayList;
import java.util.List;
public class FourQueens
{
private int boardSize;
private int[] board;
public FourQueens(int boardSize)
{
this.boardSize = boardSize;
this.board = new int[boardSize];
}
public List<List<String>> solve()
{
List<List<String>> solutions = new ArrayList<>();
placeQueen(0, solutions);
return solutions;
}
private void placeQueen(int row, List<List<String>> solutions)
{
if (row == boardSize)
{
solutions.add(createSolution());
return;
}
for (int col = 0; col < boardSize; col++)
{
if (isSafe(row, col))
{
board[row] = col;
placeQueen(row + 1, solutions);
}
}
}
private boolean isSafe(int row, int col)
{
for (int i = 0; i < row; i++)
{
if (board[i] == col || Math.abs(row - i) == Math.abs(col - board[i]))
{
return false;
}
}
return true;
}
private List<String> createSolution()
{
List<String> solution = new ArrayList<>();
for (int i = 0; i < boardSize; i++)
{
StringBuilder row = new StringBuilder();
for (int j = 0; j < boardSize; j++)
{
row.append(j == board[i] ? "|1" : "| ");
}
row.append("|");
solution.add(row.toString());
solution.add("+-" + "-+".repeat(boardSize));
}
return solution;
}
}
Editor is loading...