-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.py
43 lines (36 loc) · 1.07 KB
/
sudoku.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
# Sudoku, recursion, backtacking. from YT video Computerphile
import numpy as np
def possible(row, col, n):
# return True if n is a valid candidate for cell at grid[row][col]
for i in range(9):
if grid[row][i]==n or grid[i][col]==n:
return False
row = (row//3)*3
col = (col//3)*3
for i in range(3):
for j in range(3):
if grid[row+i][col+j] == n:
return False
return True
def solve():
for row in range(9):
for col in range(9):
if grid[row][col] == 0:
for n in range(1,10):
if possible(row, col, n):
grid[row][col] = n
solve()
grid[row][col] = 0 # no possible candidate for grid[row][col]
return
print(np.matrix(grid))
return
grid= [[0, 0, 0, 0, 0, 0, 5, 0, 0],
[0, 7, 1, 6, 8, 0, 0, 0, 0],
[0, 0, 0, 2, 5, 0, 8, 0, 3],
[0, 0, 9, 0, 0, 8, 4, 0, 0],
[0, 0, 2, 0, 1, 0, 3, 0, 0],
[0, 8, 0, 5, 0, 0, 0, 2, 0],
[4, 0, 5, 8, 3, 0, 0, 0, 0],
[0, 0, 0, 4, 9, 0, 1, 3, 0],
[0, 0, 8, 0, 0, 0, 0, 0, 0]]
solve()