-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsudoku.py
More file actions
69 lines (59 loc) · 1.83 KB
/
sudoku.py
File metadata and controls
69 lines (59 loc) · 1.83 KB
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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 21:39:12 2020
@author: rcxsm
"""
#https://towardsdatascience.com/solve-sudokus-automatically-4032b2203b64
sudoku = [
[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, 0, 7, 5, 0],
[3, 8, 0, 0, 7, 0, 0, 4, 2]]
def printsudoku():
print("\n\n\n\n\n")
for i in range(len(sudoku)):
line = ""
if i == 3 or i == 6:
print("---------------------")
for j in range(len(sudoku[i])):
if j == 3 or j == 6:
line += "| "
line += str(sudoku[i][j])+" "
print(line)
def findNextCellToFill(sudoku):
for x in range(9):
for y in range(9):
if sudoku[x][y] == 0:
return x, y
return -1, -1
def isValid(sudoku, i, j, e):
rowOk = all([e != sudoku[i][x] for x in range(9)])
if rowOk:
columnOk = all([e != sudoku[x][j] for x in range(9)])
if columnOk:
secTopX, secTopY = 3*(i//3), 3*(j//3)
for x in range(secTopX, secTopX+3):
for y in range(secTopY, secTopY+3):
if sudoku[x][y] == e:
return False
return True
return False
def solveSudoku(sudoku, i=0, j=0):
i, j = findNextCellToFill(sudoku)
if i == -1:
return True
for e in range(1, 10):
if isValid(sudoku, i, j, e):
sudoku[i][j] = e
if solveSudoku(sudoku, i, j):
return True
sudoku[i][j] = 0
return False
printsudoku()
solveSudoku(sudoku)
printsudoku()