Answer
To modify the EightQueens.py code to find all possible solutions, we need to make changes in the search method. Instead of just returning True when a solution is found, we need to store the solution and continue searching for more solutions.
Here's the modified code:
from tkinter import *
SIZE = 8 # The size of the chessboard
class EightQueens:
def __init__(self):
self.solutions = [] # List to store all solutions
self.queens = SIZE * [-1] # Queen positions
self.search(0) # Search for solutions from row 0
self.display_solutions()
# Display solutions in separate windows
def display_solutions(self):
for i, solution in enumerate(self.solutions):
window = Tk() # Create a window for each solution
window.title("Solution " + str(i + 1)) # Set a title for the window
for row in range(SIZE):
for col in range(SIZE):
if solution[row] == col:
Label(window, bg="white", width=5, height=2).grid(row=row, column=col)
else:
Label(window, bg="red", width=5, height=2).grid(row=row, column=col)
window.mainloop()
# Search for solutions starting from a specified row
def search(self, row):
if row == SIZE: # Stopping condition
self.solutions.append(self.queens.copy()) # Store the solution
return
for col in range(SIZE):
self.queens[row] = col # Place it at (row, col)
if self.is_valid(row, col):
self.search(row + 1)
# Check if a queen can be placed at row i and column j
def is_valid(self, row, col):
for i in range(row):
if self.queens[i] == col or \
self.queens[i] - i == col - row or \
self.queens[i] + i == col + row:
return False # There is a conflict
return True # No conflict
EightQueens() # Create GUI
```
The main modification is in the search method. Instead of returning True when a solution is found, we store the solution in the self.solutions list using the copy method. Then we continue searching for more solutions by calling the search method recursively with the next row.
After finding all the solutions, we call the display_solutions method, which creates a separate window for each solution and displays it on a chessboard.
Work Step by Step
No explain needed