An implementation of the N-Queens problem using a Genetic Algorithm (GA) to find valid solutions for different board sizes.
- Features
- Prerequisites
- Usage
- Algorithm Overview
- Technical Implementation
- Scalable Solution: Supports customizable N×N board sizes.
- Genetic Algorithm Optimization:
- Implements selection, crossover, and mutation techniques.
- Prioritizes valid solutions with minimal computation.
- Python 3.7 or higher
- NumPy
Run the program to solve the N-Queens problem:
python n_queens_ga.py
Follow the prompts to:
- Set the board size (e.g.,
N = 8
for an 8x8 chessboard). - Choose Genetic Algorithm parameters (mutation rate, population size, etc.).
Output:
- Prints the solved board in a matrix format.
- Selection: Chooses the fittest individuals based on a fitness function that minimizes conflicts.
- Crossover: Combines parent solutions to produce offspring.
- Mutation: Introduces randomness to explore diverse solutions.
- Fitness Evaluation: Calculates the number of conflicts for each solution and prioritizes the least conflicting ones.
Key Functions:
- Initialization:
def initialize_population(size, n): return [random_permutation(n) for _ in range(size)]
- Fitness Function:
Evaluates the number of queens attacking each other.
def calculate_fitness(board): # Counts row, column, and diagonal conflicts
- Crossover and Mutation: Introduces variety and combines solutions to find optimal configurations.