-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sudoku.py
107 lines (87 loc) · 2.71 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# -*- coding: utf-8 -*-
"""
Port of Bob Carpenter's Sudoku solver. Original
available at https://bob-carpenter.github.io/games/sudoku/java_sudoku.html
All credit goes to him, I just hacked a python version of it.
Created on Sun Dec 3 18:47:26 2017
@author: Stephen
"""
import numpy as np
from tco import with_continuations
def legal(i, j, v, cells):
"""
Check the legality of a proposed move
"""
# First check the row
for k in range(9):
if cells[i][k] == v:
return False
# Now check the column
for k in range(9):
if cells[k][j] == v:
return False
# Now check the box
boxRowOffset = (i // 3) * 3
boxColOffset = (j // 3) * 3
for k in range(3):
for m in range(3):
if cells[boxRowOffset + k][boxColOffset + m] == v:
return False
# If we survived all of this, good
return True
def parseProblem(initstate):
"""
Initialise the board
"""
cells = np.zeros((9,9),dtype=int)
# For each input value we get, add it to the board
for arg in initstate:
i = int(arg[0])
j = int(arg[1])
v = int(arg[2])
cells[i][j] = v
return(cells)
def displayBoard(cells):
"""
Pretty print of the board state
"""
for i in range(9):
if i % 3 == 0:
print(' -----------------------')
for j in range(9):
if j % 3 == 0:
print('| ', end='')
val = ' ' if cells[i][j] == 0 else cells[i][j]
print(val, end='')
print(' ', end='')
print('| ')
print(' -----------------------')
@with_continuations()
def solve(i, j, cells, self = None):
"""
Workhorse function, this makes a move and calls the
legality-checker. If it turns out to not be legal, blank the cell and
return to the previous state
"""
if i == 9:
i = 0
if j + 1 == 9:
return True
if cells[i][j] != 0:
return self(i+1, j, cells)
for val in range(1, 10):
if legal(i, j, val, cells):
cells[i][j] = val
if self(i+1, j, cells):
return True
cells[i][j] = 0
return False
if __name__ == '__main__':
state = ['014', '023', '037', '069', '088', '125',
'143', '211', '263', '306', '342', '357',
'404', '427', '461', '483', '535', '544',
'589', '622', '673', '745', '764', '805',
'824', '851', '862', '876']
board = parseProblem(state)
solve(0, 0, board)
displayBoard(board)