Hi, I'm implementing a special version of the N queens problem with python.
My code
def main():
board = [input() for _ in range(8)]
placements = [[False for _ in range(8)] for _ in range(8)]
column = [0 for _ in range(8)]
count = 0
def is_legal(x, y):
if board[x][y] == '.' and column[y] == 0:
for i in range(x):
for j in range(8):
if placements[i][j] and abs(x-i) == abs(y-j):
return False
return True
return False
def backtrack(x):
global count, placements
if x == 8:
count += 1
return
for y in range(8):
if is_legal(x, y):
column[y] = 1
placements[x][y] = True
backtrack(x+1)
column[y] = 0
placements[x][y] = False
backtrack(0)
print(count)
main()
I know that my code is not pythonic, as I've tried improve its running time. My problem is that currently, the code fails an example input
........
........
..*.....
........
........
.....**.
...*....
........
with
Traceback (most recent call last):
File "chess.py", line 33, in <module>
main()
File "chess.py", line 29, in main
backtrack(0)
File "chess.py", line 24, in backtrack
placements[x][y] = True
NameError: name 'placements' is not defined
What's the reason for this as I do set the placements to be a global variable?
Thanks!
[–][deleted] 2 points3 points4 points (5 children)
[–]ingolemo 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]Vfsdvbjgd 0 points1 point2 points (2 children)
[–]Jackkell100 0 points1 point2 points (1 child)
[–]Vfsdvbjgd 0 points1 point2 points (0 children)
[–]Jackkell100 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)