-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource code.py
More file actions
52 lines (42 loc) · 1.13 KB
/
source code.py
File metadata and controls
52 lines (42 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
backtracks=0
def findnextcelltofill(grid):
for i in range(9):
for j in range(9):
if grid[i][j]==0:
return(i,j)
return -1,-1
def isvalid(grid,i,j,e):
rowok=all([grid[i][x]!=e for x in range(9)])
if rowok:
columnok=all([grid[x][j]!=e for x in range(9)])
if columnok:
sectopx,sectopy=3*(i//3),3*(j//3)
for x in range(sectopx,sectopx+3):
for y in range(sectopy,sectopy+3):
if grid[x][y]==e:
return False
return True
return False
def solvesudoku(grid,i=0,j=0):
global backtracks
i,j=findnextcelltofill(grid)
if i==-1:
return True
for e in range(1,10):
if isvalid(grid,i,j,e):
grid[i][j]=e
if solvesudoku(grid,i,j):
return True
backtracks +=1
grid[i][j]=0
return False
def printsudoku(grid):
for row in grid:
print(row)
return
l1=[]
for i in range(9):
l1.append(list(map(int,input().split())))
solvesudoku(l1)
printsudoku(l1)
print ('Backtracks = ', backtracks)