01.n Queens Problem
01.n Queens Problem
Aim:
To write a python program to solve n-Queens Problem to demonstrate the intelligent problem
solving.
Description:
The N-Queens problem is a classic combinatorial puzzle that asks for the placement of N
queens on an NxN chessboard in such a way that no two queens threaten each other. This means
no two queens can share the same row, column, or diagonal.
Algorithm:
1. Start with an empty NxN chessboard filled with empty cells ('.').
2. Begin with the first row (row 0).
3. For each cell in the current row (from left to right):
a. Check if it's safe to place a queen in that cell (no other queens threaten it).
b. If safe, place a queen in the cell ('Q') and move to the next row.
c. If not safe, move to the next cell.
4. Repeat steps 3 until:
a. All N rows have queens placed successfully, in which case, you have a valid solution.
b. You've explored all possibilities in the current row without finding a solution.
5. If a valid solution is found, record it.
6. Backtrack to the previous row, remove the queen from the current cell, and explore other
possibilities.
7. Continue this process until you've explored all possibilities for the first row.
8. Return the list of all valid solutions found.
Program:
def solve_n_queens(n):
def is_safe(board, row, col):
# Check the column
for i in range(row):
if board[i][col] == 'Q':
return False
return True
def backtrack(row):
if row == n:
solutions.append(["".join(row) for row in board])
return
def print_solutions(solutions):
for i, solution in enumerate(solutions):
print(f"Solution {i + 1}:")
for row in solution:
print(row)
print("\n")
if __name__ == "__main__":
n = int(input("Enter the number of queens (N): "))
solutions = solve_n_queens(n)
print(f"Found {len(solutions)} solutions:")
print_solutions(solutions)
Sample Output:
Enter the number of queens (N): 4
Found 2 solutions:
Solution 1:
.Q..
...Q
Q...
..Q.
Solution 2:
..Q.
Q...
...Q
.Q..