-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve.py
72 lines (55 loc) · 1.47 KB
/
solve.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
N = 9
UNASSIGNED = 0
board = []
def solve_sudoku():
find, row, col = find_unassigned()
if find == False:
return True
for num in range(1, 10):
if is_safe(row, col, num):
board[row][col] = num
if solve_sudoku():
return True
board[row][col] = UNASSIGNED
return False
def find_unassigned():
for i in range(9):
for j in range(9):
if board[i][j] == UNASSIGNED:
return True, i, j
return False, 10, 10
def is_safe(row, col, num):
return used_in_row(row, num) == False & \
used_in_column(col, num) == False & \
used_in_sub_board(row, col, num) == False & \
board[row][col] == UNASSIGNED
def used_in_row(row, num):
for i in range(9):
if board[row][i] == num:
return True
return False
def used_in_column(column, num):
for i in range(9):
if board[i][column] == num:
return True
return False
def used_in_sub_board(row, col, num):
r = row // 3
c = col // 3
for i in range(3):
for j in range(3):
if board[i + r][j + c] == num:
return True
return False
def print_board():
for i in range(9):
for j in range(9):
print(board[i][j], end=" ")
print("")
def solve(sudoku):
global board
board = sudoku
if solve_sudoku():
print_board()
else:
print("No Solution Exist!!")