FourQueens

mail@pastecode.io avatar
unknown
java
a year ago
1.6 kB
0
Indexable
Never
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;
    }
}