-
Notifications
You must be signed in to change notification settings - Fork 2
/
sudoku.py
66 lines (50 loc) · 1.92 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
import numpy as np
class Sudoku:
def __init__(self, board: np.array) -> object:
self._board = board
def __len__(self):
return len(self._board)
def set_value(self, pos: tuple, value: int) -> bool:
if not self.is_valid(pos=pos, value=value):
return False
self._board[pos] = value
return True
def get_value(self, pos: tuple) -> int:
return self._board[pos]
def is_valid(self, pos: tuple, value: int) -> bool:
"""
this function checks the Constrains on every number that we try in the way to the solution
:param pos:
:param value:
:return:
"""
if value == 0:
return True
for i in range(len(self._board[0])):
if self._board[pos[0]][i] == value and pos[1] != i:
return False
# check COL
for i in range(len(self._board)):
if self._board[i][pos[1]] == value and pos[0] != i:
return False
# check BOX (the 3*3 must contain all integer's from 1-9 no duplicates)
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if self._board[i][j] == value and (i, j) != pos:
return False
return True
def print_board(self):
for i in range(len(self._board)):
# after every 3 rows it will draw horizontal line
if (i % 3 == 0) and i != 0:
print("- - - - - - - - - - - - ")
for j in range(len(self._board[0])):
# after every 3 Columns it will draw a diagonal line
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(self._board[i][j])
else:
print(str(self._board[i][j]) + " ", end="")