-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsudoku_alg.py
70 lines (60 loc) · 2.31 KB
/
sudoku_alg.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
def print_board(board):
'''Prints the board'''
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 and returns its position as a tuple'''
for i in range (9):
for j in range (9):
if board[i][j] == 0:
return i,j
def valid(board, pos, num):
'''Whether a number is valid in that cell, returns a bool'''
for i in range(9):
if board[i][pos[1]] == num and (i, pos[1]) != pos: #make sure it isn't the same number we're checking for by comparing coords
return False
for j in range(9):
if board[pos[0]][j] == num and (pos[0], j) != pos: #Same row but not same number
return False
start_i = pos[0] - pos[0] % 3 #ex. 5-5%3 = 3 and thats where the grid starts
start_j = pos[1] - pos[1] % 3
for i in range(3):
for j in range(3): #adds i and j as needed to go from start of grid to where we need to be
if board[start_i + i][start_j + j] == num and (start_i + i, start_j + j) != pos:
return False
return True
def solve(board):
'''Solves the Sudoku board via the backtracking algorithm'''
empty = find_empty(board)
if not empty: #no empty spots are left so the board is solved
return True
for nums in range(9):
if valid(board, empty,nums+1):
board[empty[0]][empty[1]] = nums+1
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
if __name__ == '__main__':
board = [
[0, 0, 0, 0, 0, 0, 2, 0, 0],
[0, 8, 0, 0, 0, 7, 0, 9, 0],
[6, 0, 2, 0, 0, 0, 5, 0, 0],
[0, 7, 0, 0, 6, 0, 0, 0, 0],
[0, 0, 0, 9, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 2, 0, 0, 4, 0],
[0, 0, 5, 0, 0, 0, 6, 0, 3],
[0, 9, 0, 4, 0, 0, 0, 7, 0],
[0, 0, 6, 0, 0, 0, 0, 0, 0]
]
solve(board)
print_board(board)