I first implemented a zero matrix indicating that all the positions of the chessboard are initially available
n=int(input())
answer=[]
restrictedIndices=[[0 for i in range(n)] for j in range(n)]
dp(n,0,restrictedIndices,answer)
and then I implemented three functions to fill the restrictedIndices
def columnFill(restrictedIndices,row,column,n):
o=column
restrictedIndices[row][o]=1
while o+1<n:
o+=1
restrictedIndices[row][o]=1
o=column
while o-1>=0:
o-=1
restrictedIndices[row][o]=1
o=column
return restrictedIndices
def rowFill(restrictedIndices,row,column,n):
o=row
restrictedIndices[o][column]=1
while o+1<n:
o+=1
restrictedIndices[o][column]=1
o=row
while o-1>=0:
o-=1
restrictedIndices[o][column]=1
o=row
return restrictedIndices
def diagonalFill(restrictedIndices,row,column,n):
o=row
p=column
restrictedIndices[o][column]=1
while o+1<n and p+1<n:
o+=1
p+=1
restrictedIndices[o][p]=1
o=row
p=column
while o-1>=0 and p+1<n:
o-=1
p+=1
restrictedIndices[o][p]=1
o=row
p=column
while o+1<n and p-1>=0:
o+=1
p-=1
restrictedIndices[o][p]=1
o=row
p=column
while o-1>=0 and p-1>=0:
o-=1
p-=1
restrictedIndices[o][p]=1
o=row
p=column
return restrictedIndices
and then the recursive function
def dp(n,row,restrictedIndices,answer):
print(restrictedIndices)
if row==n:
print("yes i got a solution")
return -1
print(restrictedIndices)
for i in range(n):
if restrictedIndices[row][i]==1:
print("rejected",(row,i))
continue
else:
x=[i for i in restrictedIndices]
print(row,i)
columnFill(restrictedIndices,row,i,n)
rowFill(restrictedIndices,row,i,n)
diagonalFill(restrictedIndices,row,i,n)
dp(n,row+1,restrictedIndices,answer)
I am getting wrong output and I would kindly like to know if we can solve the problem this way and if there is a better alternative. I hope I could understand how recursion and Backtracking works through the solution