N-Queens Problem Based Monte Carlo Algorithm

Community Article Published January 11, 2025

The N-Queens Problem is a classic combinatorial optimization problem. The goal is to place N queens on an N × N chessboard such that no two queens threaten each other. This means:

  • No two queens can be in the same row.
  • No two queens can be in the same column.
  • No two queens can be on the same diagonal.

image/png

A Monte Carlo algorithm provides a probabilistic approach to solving the problem by generating random solutions and iteratively improving them.

Monte Carlo Algorithm for N-Queens Problem

  1. Initialize variables

    • n: Number of queens (and board size).
    • max_trials: Maximum number of iterations for the Monte Carlo simulation.
    • best_solution: An empty list to store the best board configuration found so far.
    • min_conflicts: Set to a high value (e.g., n * n).
  2. For each trial from 1 to max_trials
    a. Generate a random initial board configuration

    • Place one queen in each column at a random row.
    • Store the board as a list board where the index represents the column, and the value at that index represents the row position of the queen in that column.

    b. Compute conflicts for the initial board

    • Count the number of conflicting pairs of queens (queens attacking each other).

    c. If no conflicts (conflicts == 0)

    • Return the current board configuration as a solution.
  3. Iteratively reduce conflicts

    • While max_steps not exceeded:
      a. Select a column with the highest number of conflicts.
      b. Find a new row for the selected column that minimizes conflicts.
      c. Update the board configuration and recompute conflicts.
      d. If conflicts == 0, return the board as a solution.
  4. Update best_solution if current board has fewer conflicts than min_conflicts.

  5. If no solution found after max_trials, return best_solution.

Steps of the N-Queens Problem Based Monte Carlo Algorithm

Step 1: Initialization

  1. Select N: Choose the size of the chessboard (N).
  2. Generate an initial random configuration:
    • Place one queen randomly in each row.
    • Ensure that there is exactly one queen per row to simplify the problem, but allow conflicts in columns and diagonals.

Step 2: Evaluate the Objective Function

  1. Count conflicts:
    • For each queen, count the number of other queens in the same column and diagonals.
    • The total number of conflicts is the sum of all these counts.
  2. Check for a solution:
    • If the total number of conflicts is zero, a valid solution has been found, and the algorithm terminates.

Step 3: Iterative Improvement

  1. Perturb the configuration:
    • Randomly select a queen.
    • Move it to another column in the same row.
    • After each move, reevaluate the total number of conflicts.
  2. Accept or reject the new configuration:
    • If the new configuration has fewer conflicts, accept the move.
    • If the new configuration has more conflicts, accept it with a small probability to avoid getting stuck in local minima (this is inspired by simulated annealing).

Step 4: Repeat Until Convergence

  1. Continue generating new configurations and evaluating conflicts until:
    • A solution with zero conflicts is found.
    • A maximum number of iterations is reached (if no solution is found).

Explanation of Key Concepts

Random Initialization

The algorithm starts with a completely random placement of queens. This ensures that the algorithm explores a large portion of the search space.

Conflict Evaluation

Conflicts are evaluated by counting how many queens are attacking each other. Two queens attack each other if:

  • They are in the same column.
  • They are on the same diagonal (difference between row and column indices is the same).

Probabilistic Acceptance

Monte Carlo algorithms rely on randomness and probability. Even if a move increases the number of conflicts, it may be accepted with a small probability. This prevents the algorithm from getting stuck in local optima.

Termination Condition

The algorithm terminates when either:

  • A valid solution (zero conflicts) is found.
  • A predefined number of iterations is reached, indicating that the algorithm may not find a solution in a reasonable amount of time.

Pseudocode

function MonteCarlo_NQueens(N):
    board = generate_random_board(N)
    iterations = 0
    max_iterations = 10000

    while iterations < max_iterations:
        conflicts = evaluate_conflicts(board)
        if conflicts == 0:
            return board  # Solution found
        
        row = random_row()
        new_column = random_column()
        move_queen(board, row, new_column)
        iterations += 1

    return None  # No solution found within the maximum iterations

Example

Input:

  • N = 8 (8-Queens Problem)

Initial Configuration:

  • Queens are randomly placed in each row: [(0, 1), (1, 3), (2, 5), (3, 7), (4, 2), (5, 0), (6, 6), (7, 4)]

Iteration 1:

  • Total conflicts = 5
  • Randomly choose a queen and move it to reduce conflicts.
  • New configuration: [(0, 1), (1, 3), (2, 5), (3, 7), (4, 6), (5, 0), (6, 4), (7, 2)]
  • Total conflicts = 2

Iteration 2:

  • Total conflicts = 2
  • Continue moving queens and evaluating until conflicts = 0.

Final Configuration:

  • Solution: [(0, 4), (1, 2), (2, 7), (3, 3), (4, 6), (5, 0), (6, 1), (7, 5)]
  • Total conflicts = 0

Step-by-Step Diagram Prompts for the Algorithm

Step 1: Initialization

Prompt: "Generate an 8x8 chessboard with random placement of 8 queens, one queen per row. Indicate the initial random configuration with the queens marked as black dots in different columns. Label the chessboard as 'Initial Random Configuration'."

image/png

Step 2: Conflict Evaluation

Prompt: "Generate the same 8x8 chessboard as above with queens placed in different columns, and highlight the conflicts using red arrows between queens that are in the same column or on the same diagonal. Label the total number of conflicts as 'Total Conflicts = X'."

image/png

Step 3: Iterative Improvement – Random Queen Selection

Prompt: "Generate the 8x8 chessboard with queens placed randomly, and highlight one randomly selected queen using a yellow circle. Label the step as 'Select a Random Queen for Movement'."

image/png

Step 4: Iterative Improvement – Move Queen to a New Position

Prompt: "Generate the same chessboard with the selected queen (highlighted in yellow) moved to a different column in the same row. Show the new position with a green dot and indicate fewer conflicts using fewer red arrows. Label this step as 'Move Queen to Reduce Conflicts'."

image/png

Step 5: Re-evaluate Conflicts

Prompt: "Generate the updated 8x8 chessboard showing the new placement of queens. Use fewer red arrows to indicate reduced conflicts, and label the total conflicts as 'Total Conflicts = Y'."

image/png

Step 6: Repeat Until Zero Conflicts or Max Iterations Reached

Prompt: "Show a sequence of three 8x8 chessboards: the initial random configuration, an intermediate configuration with fewer conflicts, and the final solution with zero conflicts. Label the sequence as 'Iteration Process: Initial → Intermediate → Final Solution'."

image/png

Step 7: Final Solution (Zero Conflicts)

Prompt: "Generate an 8x8 chessboard with a valid solution where no two queens attack each other. Ensure no red arrows are present, and label the chessboard as 'Final Solution – Zero Conflicts'."

image/png

Step 8: Fully Compiled Diagram

image/png

Advantages

  1. Simple to implement: The algorithm is easy to understand and code.
  2. Scalable: It can be applied to large N without significant modifications.
  3. Good for large search spaces: Since it uses randomness, it can explore large search spaces effectively.

Disadvantages

  1. No guarantee of finding a solution: The algorithm may not always find a solution, especially for large N or if the maximum number of iterations is too small.
  2. High variability in performance: Depending on the random initialization, the time to find a solution can vary significantly.

Applications

The N-Queens problem and its variants have applications in:

  1. Parallel processing: Assigning tasks to processors in a way that avoids conflicts.
  2. Constraint satisfaction problems: Solving problems with complex constraints, such as scheduling.
  3. AI and machine learning: Designing search algorithms and optimization techniques.

Conclusion

The Monte Carlo algorithm for the N-Queens problem is an effective probabilistic approach that leverages randomness to find solutions. While it does not guarantee success, it provides a practical method for solving large instances of the problem efficiently. By iteratively generating and improving random configurations, the algorithm explores a wide search space and can often find solutions quickly.