-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_9_sudoku_solver_simpler.py
84 lines (73 loc) · 2.46 KB
/
_9_sudoku_solver_simpler.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
class Board:
def __init__(self, board):
self.board = board
def __str__(self):
board_str = ''
for row in self.board:
row_str = [str(i) if i else '*' for i in row]
board_str += ' '.join(row_str)
board_str += '\n'
return board_str
def find_empty_cell(self):
for row, contents in enumerate(self.board):
try:
col = contents.index(0)
return row, col
except ValueError:
pass
return None
def valid_in_row(self, row, num):
return num not in self.board[row]
def valid_in_col(self, col, num):
return all(
self.board[row][col] != num
for row in range(9)
)
def valid_in_square(self, row, col, num):
row_start = (row // 3) * 3
col_start=(col // 3) * 3
for row_no in range(row_start, row_start + 3):
for col_no in range(col_start, col_start + 3):
if self.board[row_no][col_no] == num:
return False
return True
def is_valid(self, empty, num):
row, col = empty
valid_in_row = self.valid_in_row(row, num)
valid_in_col = self.valid_in_col(col, num)
valid_in_square = self.valid_in_square(row, col, num)
return all([valid_in_row, valid_in_col, valid_in_square])
def solver(self):
if (next_empty := self.find_empty_cell()) is None:
return True
else:
for guess in range(1, 10):
if self.is_valid(next_empty, guess):
row, col = next_empty
self.board[row][col] = guess
if self.solver():
return True
self.board[row][col] = 0
return False
def solve_sudoku(board):
gameboard = Board(board)
print(f'\nPuzzle to solve:\n{gameboard}')
if gameboard.solver():
print('\nSolved puzzle:')
print(gameboard)
else:
print('\nThe provided puzzle is unsolvable.')
return gameboard
if __name__ == '__main__':
puzzle = [
[1, 0, 0, 2, 0, 0, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
]
solve_sudoku(puzzle)