# Sir, I tried to write below program which solves a Sudoku puzzle using backtracking method, I saw your tutorial but I'm not getting where I have done

h_duddu

suduko=[[0,0,0,8,0,0,1,2,0],
[0,1,0,0,4,0,8,6,0],
[0,0,0,0,0,1,0,0,4],
[0,0,7,0,1,0,9,3,0],
[1,0,4,2,9,0,0,0,0],
[0,0,9,5,0,3,0,1,0],
[4,6,1,0,7,0,0,5,8],
[3,7,5,0,6,0,0,9,1],
[2,9,8,1,0,5,0,0,0]]
def is_it_possible(i,j,num):
#if num is 0<num<10 then check for following conditions else move to next block
#row checking
#coloumn checking
#matrix checking**
#if no number possible backtrack
#if not move num from 1 to 9
for k in range(0,9):
#coloumn checking:)
if suduko[i][k]==num:
return False
for k in range(0,9):
#row checking
if suduko[k][j]==num:
return False
#for checking smaller matrix we need to get i from nearby lower multiplier of 3 and higher multiplier of 3
mat_min_i=(i//3)*3
mat_min_j=(j//3)*3
for x in range(mat_min_i,mat_min_i+3):
for y in range(mat_min_j,mat_min_j+3):
if suduko[x][y]==num:
return False
return True
def number_unassigned(i,j):
num_unassigned=0
for x in range(0,9):
for y in range(0,9):
if suduko[i][j]==0:
row=i
col=j
num_unassigned=1
a=[row,col,num_unassigned]
return a
a=[-1,-1,num_unassigned]
return a
def suduko_filler():
#first traverse through every box
#if already number exists just move to next
#else check for numbers from 1 to 9:
# if is_it_possible gives true move to next else
#go to previous changed one and check for another possibility
row=0
col=0
a=number_unassigned(row,col)
row=a[0]
col=a[1]
if a[2]==0:
return True
for i in range(1,10):
if is_it_possible(row,col,i):
suduko[row][col]=i
#print_suduko(suduko)
if suduko_filler():
return True
suduko[row][col]=0
return False

def print_suduko():
for i in range(9):
print(suduko[i])
if suduko_filler():
print_suduko()
else:
print("no solution")

### Answers

•    Aakhya Singh

You have given wrong variable names for row and column in the number_unassigned function. The function should be written as below.

```def number_unassigned(i,j):
num_unassigned=0
for x in range(0,9):
for y in range(0,9):
if suduko[x][y]==0:
i=x
j=y
num_unassigned=1
a=[i,j,num_unassigned]
return a
a=[-1,-1,num_unassigned]
return a
```

• Thanks for showing my mistakes!!!!!!
- h_duddu

Download Our App.
Write your answer

Welcome.please sign up.