-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku_solver.py
114 lines (84 loc) · 3.4 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
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
108
109
110
111
112
113
114
class SudokuBoard:
def __init__(self, board):
self.board = board
def solve(self):
''' Automatically solves the board. '''
# find an empty position
position = self.find_empty()
# if it doesn't find a position it returns true
if not position:
return True
# otherwise, take that position
else:
row, column = position
# tries to solve the board, using recursion
for i in range(1,10):
# check if the number can be placed in that position
if self.is_valid(i, row, column):
# put the number in that position
self.board[row][column] = i
# calls the function recursively
if self.solve():
return True
# If the number cannot be placed there,
# it will come back and remove the number
self.board[row][column] = 0
return False
def is_valid(self, num, row, column):
''' Check if a number can be placed in a certain position.
Returns:
boolean: True if number can be placed otherwise False.
'''
# check the row for incompatibilities
for i in range(9):
if self.board[row][i] == num and column != i:
return False
# check the column for incompatibilities
for i in range(9):
if self.board[i][column] == num and row != i:
return False
# check the box for for incompatibilities
box_x_position = column // 3
box_y_position = row // 3
for x in range(box_y_position*3, box_y_position*3 + 3):
for y in range(box_x_position * 3, box_x_position*3 + 3):
if self.board[x][y] == num and (x,y) != (column, row):
return False
return True
def print_board(self):
''' Print the board in the terminal. '''
for row in range(9):
if row % 3 == 0 and row != 0:
print("-------+--------+------")
for column in range(9):
if column % 3 == 0 and column != 0:
print(" | ", end="")
if column == 8:
print(self.board[row][column])
else:
print(str(self.board[row][column]) + " ", end="")
def find_empty(self):
''' Find an empty position in the board.
Returns:
tuple (int, int): row and column of the empty position.
None: if there are no empty positions.
'''
# searches for and returns the first empty position it finds
for row in range(9):
for column in range(9):
if self.board[row][column] == 0:
return (row, column)
return None
# example
board = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]
sudoku_board = SudokuBoard(board)
sudoku_board.solve()
sudoku_board.print_board()