I am currently writing an eight queens problem solving algorithm.
The alogorithm is not the problem tho. Its the storing of the solutions.
I am trying to append the solutions (solutions are stored in a list of lists) to a list, but after saving the solution and continuing through the algorithm, the Values of the saved list keep changing.
I suppose the saved list and the one I am changing are somehow still "connected", but I dont know how.
Does anyone know a solution or a different approach to my saving strategy?
This is the part of the code I am having Problems with.
# The Code only gets executed if there is a valid solution.
if found_solution():
# Saving solution
solutions.append(board)
# deleting last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
# going back one Row
Reihe -= 1
# return
return
The board does look like this
board = [["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"]]
the solution list like this
solutions = []
If anyone wants to take a look at the whole code (There are a few german variables tho):
board = [["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"]]
Reihe = 0
solutions = []
last_queen = []
def found_solution():
count = 0
for i in range(4):
for j in range(4):
if board[i][j] == "D":
count += 1
if count == 4:
return True
return False
def board_clear(temp_Reihe, temp_i):
#Check Column and Row
for k in range(4):
if board[temp_Reihe][k] == "D":
return False
if board[k][temp_i] == "D":
return False
#Check Diagonals
#temp_i == x and temp_Reihe == y
st1_x = temp_i - min(temp_i, temp_Reihe)
st1_y = temp_Reihe - min(temp_i, temp_Reihe)
st2_x = temp_i - min(temp_i, 3-temp_Reihe)
st2_y = temp_Reihe + min(temp_i, 3-temp_Reihe)
while st1_x < 4 and st1_y < 4:
if board[st1_y][st1_x] == "D":
return False
st1_x += 1
st1_y += 1
while st2_x < 4 and st2_y > -1:
if board[st2_y][st2_x] == "D":
return False
st2_x += 1
st2_y -= 1
return True
def main():
global Reihe, board, solutions, last_queen
if found_solution():
#Saving solution
solutions.append(board)
#deleting last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
#going back one Row
Reihe -= 1
return
for i in range(4):
#placing Queen if valid spot
if board_clear(Reihe, i):
board[Reihe][i] = "D"
last_queen.append([Reihe,i])
Reihe += 1
main()
#delete last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
#going back one Row
Reihe -= 1
return
main()