In: Computer Science
Second Time Posting - Do not Rush to answer question - Must be done in Python - Please HELP
Write and Compile a python script to solve the 4-queens problem using the Iterative Improvement Algorithm. The code should allow for random starting, and for placed starting. Random Starting means randomly place a queen position on the chessboard. Placed Starting means asked for the user input to place a queen position on the chessboard. Display the iterations until the final solution
"The 4-Queens Problem[1] consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal."
Display the output of the python Script
#Question solution-Python program to solve 4*4 Queen
problem= First We draw the 4* 4 queen picture as
following.
Q=4 | |||
Q=4 | |||
Q=4 | |||
Q=4 |
N
=
4
def printQueen(board):
for
i
in
range
(N):
for
j
in
range
(N):
print
board[i][j],
print
def
isSafeQueen(board, row, col):
# now Check this row
on left side
for
i
in
range
(col):
if
board[row][i]
=
=
1
:
return
False
# now Check upper
diagonal on left side
for
i,
j
in
zip
(
range
(row,
-
1
,
-
1
),
range
(col,
-
1
,
-
1
)):
if
board[i][j]
=
=
1
:
return
False
# we can Check lower
diagonal on left side
for
i,
j
in
zip
(
range
(row,
N,
1
),
range
(col,
-
1
,
-
1
)):
if
board[i][j]
=
=
1
:
return
False
return
True
def
solveNQUtil(board, col):
# base case: If all
queens are placed
# then return
true
if
col
>
=
N:
return
True
# let us this column
and try placing
# In this queen in
all rows one by one
for
i
in
range
(N):
if
isSafeQueen(board, i, col):
#
Place this queen in board[i][col]
board[i][col]
=
1
#
recur to place rest of the queens
if
solveNQUtil(board, col
+
1
)
=
=
True
:
return
True
#
If placing queen in board[i][col
#
doesn't lead to a solution, then
#
queen from board[i][col]
board[i][col]
=
0
# if the queen can
not be placed in any row in
# this colum col then
return false
return
False
# This function solves the N Queen problem
using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def
solveNQ():
board
=
[ [
0
,
0
,
0
,
0
],
[
0
,
0
,
0
,
0
],
[
0
,
0
,
0
,
0
],
[
0
,
0
,
0
,
0
]
]
if
solveNQUtil(board,
0
)
=
=
False
:
print
"Solution does not exist"
return
False
printQueen(board)
return
True
output=================
0 | 0 | 1 | 0 |
1 | 0 | 0 | 0 |
0 | 0 | 0 | 0 |
0 | 1 | 0 | 0 |