-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolve.py
59 lines (52 loc) · 1.57 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
# Project to solve unique sudoku's programmatically.
# Assumes a provided sudoku has a unique solution
from typing import DefaultDict
def printBoard(board):
for row in board:
if board.index(row) % 3 == 0:
print("- - - - - - - - - - - - -")
for i in range(len(row)):
if i % 3 == 0:
print("| ", end="")
print(f"{row[i]} ", end="")
print("|")
def findNextCell(board):
d = DefaultDict()
for x in range(1,len(board)+1):
for y in range(1,len(board)+1):
if board[x-1][y-1] != 0: continue
sees = whatCellSees(board, (x,y))
count = len(sees)
d[(x,y)] = [count, sees]
try:
return sorted(d.items(),key=lambda kv: kv[1], reverse=True)[0]
except:
return None, None
def whatCellSees(board,cell):
d = DefaultDict(int)
x,y = cell
for cell in board[x-1]:
if cell != 0:
d[cell] += 1
for i in range(len(board)):
if board[i][y-1] != 0:
d[board[i][y-1]] += 1
xmod = (x-1) // 3
ymod = (y-1) // 3
for i in range(xmod*3, xmod*3+3):
for j in range(ymod*3, ymod*3+3):
if board[i][j] != 0:
d[board[i][j]] += 1
return sorted(d)
def solve(board):
find = findNextCell(board)
if not find[0]:
return board
cell, sees = find
for i in range(1,10):
if i in sees[1]: continue
board[cell[0]-1][cell[1]-1] = i
if solve(board):
return board
board[cell[0]-1][cell[1]-1] = 0
return False