-
Notifications
You must be signed in to change notification settings - Fork 49
/
sudokutools.py
170 lines (125 loc) · 4.4 KB
/
sudokutools.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint, shuffle
def print_board(board):
"""
Prints the sudoku board.
Args:
board (list[list[int]]): A 9x9 sudoku board represented as a list of lists of integers.
Returns:
None.
"""
boardString = ""
for i in range(9):
for j in range(9):
boardString += str(board[i][j]) + " "
if (j + 1) % 3 == 0 and j != 0 and j + 1 != 9:
boardString += "| "
if j == 8:
boardString += "\n"
if j == 8 and (i + 1) % 3 == 0 and i + 1 != 9:
boardString += "- - - - - - - - - - - \n"
print(boardString)
def find_empty(board):
"""
Finds an empty cell in the sudoku board.
Args:
board (list[list[int]]): A 9x9 sudoku board represented as a list of lists of integers.
Returns:
tuple[int, int]|None: The position of the first empty cell found as a tuple of row and column indices, or None if no empty cell is found.
"""
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return (i, j)
return None
def valid(board, pos, num):
"""
Checks whether a number is valid in a cell of the sudoku board.
Args:
board (list[list[int]]): A 9x9 sudoku board represented as a list of lists of integers.
pos (tuple[int, int]): The position of the cell to check as a tuple of row and column indices.
num (int): The number to check.
Returns:
bool: True if the number is valid in the cell, False otherwise.
"""
for i in range(9):
if board[i][pos[1]] == num:
return False
for j in range(9):
if board[pos[0]][j] == num:
return False
start_i = pos[0] - pos[0] % 3
start_j = pos[1] - pos[1] % 3
for i in range(3):
for j in range(3):
if board[start_i + i][start_j + j] == num:
return False
return True
def solve(board):
"""
Solves the sudoku board using the backtracking algorithm.
Args:
board (list[list[int]]): A 9x9 sudoku board represented as a list of lists of integers.
Returns:
bool: True if the sudoku board is solvable, False otherwise.
"""
empty = find_empty(board)
if not empty:
return True
for nums in range(1, 10):
if valid(board, empty, nums):
board[empty[0]][empty[1]] = nums
if solve(board): # recursive step
return True
board[empty[0]][empty[1]] = 0 # this number is wrong so we set it back to 0
return False
def generate_board():
"""
Generates a random sudoku board with fewer initial numbers.
Returns:
list[list[int]]: A 9x9 sudoku board represented as a list of lists of integers.
"""
board = [[0 for i in range(9)] for j in range(9)]
# Fill the diagonal boxes
for i in range(0, 9, 3):
nums = list(range(1, 10))
shuffle(nums)
for row in range(3):
for col in range(3):
board[i + row][i + col] = nums.pop()
# Fill the remaining cells with backtracking
def fill_cells(board, row, col):
"""
Fills the remaining cells of the sudoku board with backtracking.
Args:
board (list[list[int]]): A 9x9 sudoku board represented as a list of lists of integers.
row (int): The current row index to fill.
col (int): The current column index to fill.
Returns:
bool: True if the remaining cells are successfully filled, False otherwise.
"""
if row == 9:
return True
if col == 9:
return fill_cells(board, row + 1, 0)
if board[row][col] != 0:
return fill_cells(board, row, col + 1)
for num in range(1, 10):
if valid(board, (row, col), num):
board[row][col] = num
if fill_cells(board, row, col + 1):
return True
board[row][col] = 0
return False
fill_cells(board, 0, 0)
# Remove a greater number of cells to create a puzzle with fewer initial numbers
for _ in range(randint(55, 65)):
row, col = randint(0, 8), randint(0, 8)
board[row][col] = 0
return board
if __name__ == "__main__":
board = generate_board()
print_board(board)
solve(board)
print_board(board)