-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku_solver.py
50 lines (40 loc) · 1.03 KB
/
sudoku_solver.py
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
import sys
graph = []
blank = []
for i in range(9):
graph.append(list(map(int, sys.stdin.readline().rstrip().split())))
for i in range(9):
for j in range(9):
if graph[i][j] == 0:
blank.append((i, j))
def checkRow(x, a):
for i in range(9):
if a == graph[x][i]:
return False
return True
def checkCol(y, a):
for i in range(9):
if a == graph[i][y]:
return False
return True
def checkRect(x, y, a):
nx = x // 3 * 3
ny = y // 3 * 3
for i in range(3):
for j in range(3):
if a == graph[nx+i][ny+j]:
return False
return True
def dfs(idx):
if idx == len(blank):
for i in range(9):
print(*graph[i])
exit(0)
for i in range(1, 10):
x = blank[idx][0]
y = blank[idx][1]
if checkRow(x, i) and checkCol(y, i) and checkRect(x, y, i):
graph[x][y] = i
dfs(idx+1)
graph[x][y] = 0
dfs(0)