I first implemented a zero matrix indicating that all the positions of the chessboard are initially available
JavaScript
x
5
1
n=int(input())
2
answer=[]
3
restrictedIndices=[[0 for i in range(n)] for j in range(n)]
4
dp(n,0,restrictedIndices,answer)
5
and then I implemented three functions to fill the restrictedIndices
JavaScript
1
58
58
1
def columnFill(restrictedIndices,row,column,n):
2
o=column
3
restrictedIndices[row][o]=1
4
while o+1<n:
5
o+=1
6
restrictedIndices[row][o]=1
7
o=column
8
while o-1>=0:
9
o-=1
10
restrictedIndices[row][o]=1
11
o=column
12
return restrictedIndices
13
14
15
def rowFill(restrictedIndices,row,column,n):
16
o=row
17
restrictedIndices[o][column]=1
18
while o+1<n:
19
o+=1
20
restrictedIndices[o][column]=1
21
o=row
22
while o-1>=0:
23
o-=1
24
restrictedIndices[o][column]=1
25
o=row
26
return restrictedIndices
27
28
29
def diagonalFill(restrictedIndices,row,column,n):
30
o=row
31
p=column
32
restrictedIndices[o][column]=1
33
while o+1<n and p+1<n:
34
o+=1
35
p+=1
36
restrictedIndices[o][p]=1
37
o=row
38
p=column
39
while o-1>=0 and p+1<n:
40
o-=1
41
p+=1
42
restrictedIndices[o][p]=1
43
o=row
44
p=column
45
while o+1<n and p-1>=0:
46
o+=1
47
p-=1
48
restrictedIndices[o][p]=1
49
o=row
50
p=column
51
while o-1>=0 and p-1>=0:
52
o-=1
53
p-=1
54
restrictedIndices[o][p]=1
55
o=row
56
p=column
57
return restrictedIndices
58
and then the recursive function
JavaScript
1
19
19
1
def dp(n,row,restrictedIndices,answer):
2
print(restrictedIndices)
3
if row==n:
4
print("yes i got a solution")
5
return -1
6
print(restrictedIndices)
7
for i in range(n):
8
if restrictedIndices[row][i]==1:
9
print("rejected",(row,i))
10
continue
11
12
else:
13
x=[i for i in restrictedIndices]
14
print(row,i)
15
columnFill(restrictedIndices,row,i,n)
16
rowFill(restrictedIndices,row,i,n)
17
diagonalFill(restrictedIndices,row,i,n)
18
dp(n,row+1,restrictedIndices,answer)
19
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
Advertisement
Answer
This will not work, because of the following issues:
answer
is never populated: it can therefore be nothing else than its initial value, an empty list- Although you let
dp
return -1 when a solution is found, this value is never checked by the caller. So the caller does not know about it and goes to the next iteration of itsfor
loop - When the recursive call of
dp
returns, therestrictedIndices
list is not returned to its previous state. This means that in the next iterations of thefor
loop the condition[row][i]==1
will always be True — this cell was set to 1 during the first iteration. You should make sure that each iteration of thefor
loop starts with the exact same state ofrestrictedIndices
.
I will not post a working solution, as this is extensively documented on the internet, and recursive solutions for Python can be found also on Stack Overflow: