Reinas mínimas necesarias para cubrir todas las casillas de un tablero de ajedrez

Dadas las dimensiones de un tablero de ajedrez (N x M), determine el número mínimo de reinas necesarias para cubrir todas las casillas del tablero. Una reina puede atacar cualquier casilla a lo largo de su fila, columna o diagonales.

Ejemplos:

Input : N = 8, M = 8
Output : 5
Layout : Q X X X X X X X 
         X X Q X X X X X 
         X X X X Q X X X 
         X Q X X X X X X 
         X X X Q X X X X 
         X X X X X X X X 
         X X X X X X X X 
         X X X X X X X X 

Input : N = 3, M = 5
Output : 2
Layout : Q X X X X 
         X X X X X 
         X X X Q X 

Este artículo intenta resolver el problema de una manera muy simple sin mucha optimización.

Paso 1: Comenzando desde cualquier casilla de la esquina del tablero, encuentra una casilla «descubierta» (la casilla descubierta es una casilla que no es atacada por ninguna de las reinas ya colocadas). Si no encuentra ninguno, vaya al Paso 4.
Paso 2: Coloque una Reina en este cuadrado e incremente la variable ‘recuento’ en 1.
Paso 3: Repita el paso 1.
Paso 4: Ahora, tiene un diseño donde cada cuadrado está cubierto. Por lo tanto, el valor de ‘contar’ puede ser la respuesta. Sin embargo, es posible que pueda hacerlo mejor, ya que podría existir un mejor diseño con una menor cantidad de reinas. Por lo tanto, almacene este ‘recuento’ como el mejor valor hasta ahora y proceda a encontrar una mejor solución.
Paso 5: Retire la última reina colocada y colóquela en la siguiente celda ‘descubierta’.
Paso 6: proceda recursivamente y pruebe todos los diseños posibles. Finalmente, el que tenga el menor número de reinas es la respuesta.

Ejecute en seco el siguiente código para una mejor comprensión.

// Java program to find minimum number of queens needed
// to cover a given chess board.
  
public class Backtracking {
  
    // The chessboard is represented by a 2D array.
    static boolean[][] board;
  
    // N x M is the dimension of the chess board.
    static int N, M;
  
    // The minimum number of queens required.
    // Initially, set to MAX_VAL.
    static int minCount = Integer.MAX_VALUE;
  
    static String layout; // Stores the best layout.
  
    // Driver code
    public static void main(String[] args)
    {
        N = 8;
        M = 8;
        board = new boolean[N][M];
        placeQueen(0);
  
        System.out.println(minCount);
        System.out.println("\nLayout: \n" + layout);
    }
  
    // Finds minimum count of queens needed and places them.
    static void placeQueen(int countSoFar)
    {
        int i, j;
  
        if (countSoFar >= minCount)
              
            // We've already obtained a solution with lesser or
            // same number of queens. Hence, no need to proceed.
            return;
  
        // Checks if there exists any unattacked cells.
        findUnattackedCell : {
        for (i = 0; i < N; ++i)
            for (j = 0; j < M; ++j)
                if (!isAttacked(i, j))
  
                    // Square (i, j) is unattacked.
                    break findUnattackedCell;
  
        // All squares all covered. Hence, this 
        // is the best solution till now.
        minCount = countSoFar;
        storeLayout();
  
        return;
        }
  
        for (i = 0; i < N; ++i)
            for (j = 0; j < M; ++j) {
                if (!isAttacked(i, j)) {
  
                    // Square (i, j) is unattacked.
                    // Therefore, place a queen here.
                    board[i][j] = true; 
  
                    // Increment 'count' and proceed recursively.
                    placeQueen(countSoFar + 1);
  
                    // Remove this queen and attempt to
                    // find a better solution.
                    board[i][j] = false; 
                }
            }
    }
  
    // Returns 'true' if the square (row, col) is 
    // being attacked by at least one queen.
    static boolean isAttacked(int row, int col) 
    {
        int i, j;
  
        // Check the 'col'th column for any queen.
        for (i = 0; i < N; ++i)
            if (board[i][col])
                return true;
  
        // Check the 'row'th row for any queen.
        for (j = 0; j < M; ++j)
            if (board[row][j])
                return true;
  
        // Check the diagonals for any queen.
        for (i = 0; i < Math.min(N, M); ++i)
            if (row - i >= 0 && col - i >= 0 && 
                        board[row - i][col - i])
                return true;
            else if (row - i >= 0 && col + i < M &&
                           board[row - i][col + i])
                return true;
            else if (row + i < N && col - i >= 0 && 
                            board[row + i][col - i])
                return true;
            else if (row + i < N && col + i < M &&
                            board[row + i][col + i])
                return true;
  
        // This square is unattacked. Hence return 'false'.
        return false;
    }
  
    // Stores the current layout in 'layout' 
    // variable as String.
    static void storeLayout()
    {
        StringBuilder sb = new StringBuilder();
        for (boolean[] row : board) {
            for (boolean cell : row)
                sb.append(cell ? "Q " : "X ");
            sb.append("\n");
        }
        layout = sb.toString();
    }
}
Producción:

5

Layout: 
Q X X X X X X X 
X X Q X X X X X 
X X X X Q X X X 
X Q X X X X X X 
X X X Q X X X X 
X X X X X X X X 
X X X X X X X X 
X X X X X X X X

Publicación traducida automáticamente

Artículo escrito por sarthakmannaofficial y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *