Question

In: Computer Science

The Eight Queens Problem is a fairly old problem that has been well discussed and researched....

The Eight Queens Problem is a fairly old problem that has been well discussed and researched. The first published reference to this problem was in a German Chess magazine in 1848 by Max Bezzel. In 1850, Franz Nauck published all 92 solutions of the problem for an 8x8 board. S. Gunther in 1874 suggested a method for finding solutions by using determinants and J.W.L. Glaisher extended this method. E. Dijkstra published a detailed description of the solution of the problem as a depth-first backtracking algorithm.

The original statement of the problem ran as follows - how can we place eight queens on a regular chess board such that no queen can capture another. It turns out there is no unique solution but 92 possible solutions of which only 12 are distinct. The 12 distinct solutions can generate all other solutions through reflections and / or rotations. Here is a table that gives the size of the board, all possible solutions, and all distinct solutions.

Size All Solutions Distinct Solutions
1 1 1
2 0 0
3 0 0
4 2 1
5 10 2
6 4 1
7 40 6
8 92 12

Prompt the user to enter the size of the board. The size of the board must be a number between 1 and 8 inclusive. Keep prompting the user to enter a number in that range, if he does not get it right. For the size of the board that the user specified generate and print all possible solutions for that size. Keep a count of the number of solutions and your last line should print the total number. Here is a possible scenario:

Enter the size of board: 4

* Q * *
* * * Q
Q * * *
* * Q *

* * Q *
Q * * *
* * * Q
* Q * *

There are 2 solutions for a 4 x 4 board.

This is what I have so far, but it only prints one possible solution for the size of the board:

class Queens (object):

# initialize the board

def __init__ (self, n = 8):

self.board = []

self.n = n

for i in range (self.n):

row = []

for j in range (self.n):

row.append ('*')

self.board.append (row)

# print the board

def print_board (self):

for i in range (self.n):

for j in range (self.n):

print (self.board[i][j], end = ' ')

print ()

# check if no queen captures another

def is_valid (self, row, col):

for i in range (self.n):

if (self.board[row][i] == 'Q' or self.board[i][col] == 'Q'):

return False

for i in range (self.n):

for j in range (self.n):

row_diff = abs (row - i)

col_diff = abs (col - j)

if (row_diff == col_diff) and (self.board[i][j] == 'Q'):

return False

return True

# do a recursive backtracking solution

def recursive_solve (self, col):

if (col == self.n):

return True

else:

for i in range (self.n):

if (self.is_valid(i, col)):

self.board[i][col] = 'Q'

if (self.recursive_solve (col + 1)):

return True

self.board[i][col] = '*'

return False

# if the problem has a solution print the board

def solve (self):

for i in range (self.n):

if (self.recursive_solve(i)):

self.print_board()

def main():

# create a regular chess board

game = Queens (8)

# place the queens on the board

game.solve()

main()

Solutions

Expert Solution

Code implemented in python:

Note: Comments are written for code explanation

Filename: Queens.py

Code:

#global counter variable to count the number of possible solutions for n queens
counter = 0
#initialize the class of Queens
class Queens (object):
# initialize the board
def __init__ (self, n = 8):
self.board = []
self.n = n
for i in range (self.n):
row = []
for j in range (self.n):
row.append ('*')
self.board.append (row)

# print the board
def print_board (self):
for i in range (self.n):
for j in range (self.n):
print (self.board[i][j], end = ' ')
print ()
print()

# check if no queen captures another
def is_valid (self, row, col):
for i in range (self.n):
if (self.board[row][i] == 'Q' or self.board[i][col] == 'Q'):
return False
for i in range (self.n):
for j in range (self.n):
row_diff = abs (row - i)
col_diff = abs (col - j)
if (row_diff == col_diff) and (self.board[i][j] == 'Q'):
return False
return True

# do a recursive backtracking solution
def recursive_solve (self, col):
global counter
if (col == self.n):
#this uses the helper function to see how many queens are present
num = self.count_Queen()
if num == self.n:
  
self.print_board()
counter += 1
return True
else:
solvable = False
for i in range (self.n):
if (self.is_valid(i, col)):
self.board[i][col] = 'Q'
solvable = self.recursive_solve(col + 1) or solvable
self.board[i][col] = '*'
return

# if the problem has a solution print the board
def solve (self):
for i in range (self.n):
self.recursive_solve(i)

#this counts the numer of queens present in the solution and returns a sum
def count_Queen(self):
qsum = 0
for i in range(self.n):
qsum += self.board[i].count('Q')
return qsum
  
  
def main():
try:
  
# create a regular chess board
n = eval(input("Enter size of board: "))
print()
while n <= 0 or n > 8:
n = eval(input("Enter size of board: "))
print()
  
game = Queens (n)

# place the queens on the board
game.solve()
  
print("There are " , counter ,"solutions for a ", str(n) , "x" , str(n ), "board.")
  
#exception handling for user input
except ValueError:
print("Invalid Input.")
  
except SyntaxError:
print("invalid Input.")
except TypeError:
print("Invalid end.")
main()

Working Code Output Screenshot:

If you like my answer, hit thumbs up . Thank you.


Related Solutions

is a 25-year old female who has not been feeling well for the past 6 months....
is a 25-year old female who has not been feeling well for the past 6 months. She is frustrated that she has been gaining weight no matter how much she exercises, and complains to her mom, “I’m always cold, even if I wear my big jacket!” Furthermore, her neck appears enlarged. Her mom has hypothyroid herself, (for which she takes Thyrolar) and recognizes her daughter’s symptoms. “You should make an appointment with your doctor and get some blood work done,”...
Discuss the topic of maximizing shareholder wealth. This topic has been researched and studied for many...
Discuss the topic of maximizing shareholder wealth. This topic has been researched and studied for many years, with mixed results. For example; Irving Fisher, a prominent American Economist, argued that maximizing shareholders wealth should be management’s primary goal (Cardao-Pito, 2016). Conversely, Sollars and Tuluca (2016) suggested that shareholders should only be rewarded with returns that are “commensurate with the risk they take”. (p. 203). Briefly share your thoughts about shareholder wealth maximization. Then, explain the advantages and disadvantages of wealth...
Children's height as a function of their age has been researched so extensively that we can...
Children's height as a function of their age has been researched so extensively that we can consider known results to describe the relationship for all children in the United States. For instance, between the ages of 13 and 15, population mean height for teenage males (in inches) satisfies μy = 22 + 3x,  where x is age in years. Spread about the line is 3.1 inches. 1.  Notice that the slope of the regression line for the population is β1 = 3....
Next, discuss the topic of maximizing shareholder wealth. This topic has been researched and studied for...
Next, discuss the topic of maximizing shareholder wealth. This topic has been researched and studied for many years, with mixed results. For example; Irving Fisher, a prominent American Economist, argued that maximizing shareholders wealth should be management’s primary goal (Cardao-Pito, 2016). Conversely, Sollars and Tuluca (2016) suggested that shareholders should only be rewarded with returns that are “commensurate with the risk they take”. (p. 203). After reading the required textbook chapters for this module, briefly share your thoughts about shareholder...
Directions: The Acme Water Pump Company has a problem. The pumps are fairly expensive to make...
Directions: The Acme Water Pump Company has a problem. The pumps are fairly expensive to make and store, so the company tends to keep the inventory low. At the same time, it is important to respond to demand quickly, since a customer who wants a water pump is very likely to get one from a competitor if Acme doesn’t have one available immediately. Determine what the projected available balance, master production schedule, and the available to promise is for each...
A committee of eight people, labelled a, b,...,h, has been split into the following eight subcommittees:...
A committee of eight people, labelled a, b,...,h, has been split into the following eight subcommittees: {a,b,c,h},{c,d,e},{a,b,d,g},{c,d,e,f},{c,d,f},{b,d,g,h},{d,e,f},{c,e,f} Is it possible for each subcommittee to choose from amongst its members a chairperson, so that nobody chairs more than one subcommittee? Justify your answer.
23-year-old Josh has been suffering from extreme psoriasis for eight years. He’s tried all sorts of...
23-year-old Josh has been suffering from extreme psoriasis for eight years. He’s tried all sorts of creams to no avail but has found that sunlight has a positive effect. Pixie warns against over-exposure to sunlight and suggests Josh stops smoking and cuts down on alcohol. If he does this he might be eligible for biological treatment, in which medication is administered to attack psoriasis from inside his body, rather than applying ointments and creams externally. Cyclosporin, a potent drug, has...
What is a major corporate cost decision that has been discussed in the media in the...
What is a major corporate cost decision that has been discussed in the media in the past 6-12 months?
The value of international accounting standards has been discussed for a number of years, but with...
The value of international accounting standards has been discussed for a number of years, but with the increased global activity in business in recent history, the need for such has grown in importance. As you may have discussed in financial accounting courses or have seen in business news reports, the international standards [IFRS] have been in use by a number of countries, but not the US. The US has continued to report under GAAP, but the FASB is currently in...
Harold, a fifty-eight year old grocery store manager, had recently been waking up in the middle...
Harold, a fifty-eight year old grocery store manager, had recently been waking up in the middle of the night with abdominal pain. This was happening several nights a week. He was also experiencing occasional discomfort in the middle of the afternoon. Harold decided to schedule an appointment with his physician. The doctor listened as Harold described his symptoms and then asked Harold some questions. He noted that Harold's appetite had suffered as a result of the pain he was experiencing...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT