import
random
import
math
class
Sudoku:
def
__init__(
self
, N, K):
self
.N
=
N
self
.K
=
K
SRNd
=
math.sqrt(N)
self
.SRN
=
int
(SRNd)
self
.mat
=
[[
0
for
_
in
range
(N)]
for
_
in
range
(N)]
def
fillValues(
self
):
self
.fillDiagonal()
self
.fillRemaining(
0
,
self
.SRN)
self
.removeKDigits()
def
fillDiagonal(
self
):
for
i
in
range
(
0
,
self
.N,
self
.SRN):
self
.fillBox(i, i)
def
unUsedInBox(
self
, rowStart, colStart, num):
for
i
in
range
(
self
.SRN):
for
j
in
range
(
self
.SRN):
if
self
.mat[rowStart
+
i][colStart
+
j]
=
=
num:
return
False
return
True
def
fillBox(
self
, row, col):
num
=
0
for
i
in
range
(
self
.SRN):
for
j
in
range
(
self
.SRN):
while
True
:
num
=
self
.randomGenerator(
self
.N)
if
self
.unUsedInBox(row, col, num):
break
self
.mat[row
+
i][col
+
j]
=
num
def
randomGenerator(
self
, num):
return
math.floor(random.random()
*
num
+
1
)
def
checkIfSafe(
self
, i, j, num):
return
(
self
.unUsedInRow(i, num)
and
self
.unUsedInCol(j, num)
and
self
.unUsedInBox(i
-
i
%
self
.SRN, j
-
j
%
self
.SRN, num))
def
unUsedInRow(
self
, i, num):
for
j
in
range
(
self
.N):
if
self
.mat[i][j]
=
=
num:
return
False
return
True
def
unUsedInCol(
self
, j, num):
for
i
in
range
(
self
.N):
if
self
.mat[i][j]
=
=
num:
return
False
return
True
def
fillRemaining(
self
, i, j):
if
i
=
=
self
.N
-
1
and
j
=
=
self
.N:
return
True
if
j
=
=
self
.N:
i
+
=
1
j
=
0
if
self
.mat[i][j] !
=
0
:
return
self
.fillRemaining(i, j
+
1
)
for
num
in
range
(
1
,
self
.N
+
1
):
if
self
.checkIfSafe(i, j, num):
self
.mat[i][j]
=
num
if
self
.fillRemaining(i, j
+
1
):
return
True
self
.mat[i][j]
=
0
return
False
def
removeKDigits(
self
):
count
=
self
.K
while
(count !
=
0
):
i
=
self
.randomGenerator(
self
.N)
-
1
j
=
self
.randomGenerator(
self
.N)
-
1
if
(
self
.mat[i][j] !
=
0
):
count
-
=
1
self
.mat[i][j]
=
0
return
def
printSudoku(
self
):
for
i
in
range
(
self
.N):
for
j
in
range
(
self
.N):
print
(
self
.mat[i][j], end
=
" "
)
print
()
if
__name__
=
=
"__main__"
:
N
=
9
K
=
40
sudoku
=
Sudoku(N, K)
sudoku.fillValues()
sudoku.printSudoku()