nqueens backtracing code example
Example: nqueens backtracing
def check(row, col):
for prow in range(row):
pcol = queens[prow]
if(pcol == col or (abs(col - pcol) == abs(row - prow))):
return False
return True
def nqueens(row):
global n, ans, queens
if(row == n):
ans+=1
return
else:
for col in range(n):
if(check(row, col)):
queens.append(col)
nqueens(row+1)
queens.pop()
if __name__ == "__main__":
n = input('Enter n: ')
ans = 0
queens = []
nqueens(0)
print(ans)