1.Complete the program that solves the Eight Queens problem….
1.Complete the program that solves the Eight Queens problem. The program’s output should look similar to: |1|0|0|0|0|0|0|0| |0|0|0|0|0|0|1|0| |0|0|0|0|1|0|0|0| |0|0|0|0|0|0|0|1| |0|1|0|0|0|0|0|0| |0|0|0|1|0|0|0|0| |0|0|0|0|0|1|0|0| |0|0|1|0|0|0|0|0| Where a 1 represents a queen chess piece on the board, and a 0 represents an empty square on the board.
Answer
The Eight Queen problem is a classic puzzle in the field of computer science and mathematics. It involves placing eight queens on an 8×8 chessboard in such a way that no two queens threaten each other. In other words, no two queens should be able to attack each other by sharing the same row, column, or diagonal.
To solve this problem, we can use a recursive backtracking algorithm. The algorithm works by placing queens on the board one by one and checking if the current configuration is valid. If it is valid, we move on to the next row and repeat the process. If it is not valid, we backtrack and try a different position for the queen.
Here is a program that implements this algorithm in Python:
“`python
def is_valid(board, row, col):
# Check if there is a queen in the same column
for i in range(row):
if board[i][col] == 1:
return False
# Check if there is a queen in the upper left diagonal
i = row – 1
j = col – 1
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1
# Check if there is a queen in the upper right diagonal
i = row – 1
j = col + 1
while i >= 0 and j < len(board):
if board[i][j] == 1:
return False
i -= 1
j += 1
return True
def solve_queens(board, row):
# Base case: all queens have been placed
if row == len(board):
return True
for col in range(len(board)):
# Check if it is safe to place a queen at the current position
if is_valid(board, row, col):
# Place the queen at the current position
board[row][col] = 1
# Try to place the remaining queens
if solve_queens(board, row + 1):
return True
# If placing the queen leads to an invalid configuration, backtrack
board[row][col] = 0
return False
# Initialize the board
board = [[0] * 8 for _ in range(8)]
# Solve the Eight Queens problem
if solve_queens(board, 0):
# Print the solution
for row in board:
print("|" + "|".join(map(str, row)) + "|")
else:
print("No solution found.")
```
When you run this program, it will find a valid configuration for the Eight Queens problem and print it in the desired format, where a 1 represents a queen and a 0 represents an empty square on the board. If no solution is found, it will print "No solution found."
It is important to note that the program presented above can be generalized for any size of the chessboard. The size of the board is determined by the dimensions of the nested list `board`.