Skip to content

Commit 4967d5e

Browse files
committed
initial commit
0 parents  commit 4967d5e

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed

sudoku-solver.py

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import sys
2+
3+
board = []
4+
5+
6+
def solve():
7+
find = find_empty_cell()
8+
if not find:
9+
return True
10+
else:
11+
row, col = find
12+
13+
for i in range(1,10):
14+
if is_valid(i, (row, col)):
15+
board[row][col] = i
16+
17+
if(solve()):
18+
return True
19+
board[row][col] = 0
20+
21+
def is_valid(num, pos):
22+
#row
23+
for i in range(len(board[0])):
24+
if board[pos[0]][i] == num and pos[1] != i:
25+
return False
26+
27+
for i in range(len(board)):
28+
if board[i][pos[1]] == num and pos[0] != i:
29+
return False
30+
31+
box_x = pos[1] // 3
32+
box_y = pos[0] // 3
33+
34+
for i in range(box_y * 3, box_y * 3 + 3):
35+
for j in range(box_x * 3, box_x * 3 + 3):
36+
if board[i][j] == num and (i, j) != pos:
37+
return False
38+
39+
return True
40+
41+
def print_board():
42+
for i in range(len(board)):
43+
if i % 3 == 0 and i != 0:
44+
print("- - - - - - - - - - - -")
45+
46+
for j in range(len(board[0])):
47+
if j % 3 == 0 and j != 0:
48+
print(" | ", end="")
49+
50+
if j == 8:
51+
print(board[i][j])
52+
else:
53+
print(str(board[i][j]) + " ", end="")
54+
55+
56+
57+
def find_empty_cell():
58+
for i in range(len(board)):
59+
for j in range(len(board[0])):
60+
if board[i][j] == 0:
61+
return (i, j)
62+
return None
63+
64+
sudoko_text = ""
65+
66+
try:
67+
with open (sys.argv[1]) as file:
68+
for i, line in enumerate(file):
69+
sudoko_text += str.rstrip(line)
70+
except:
71+
print("- - - - - - - - - - - - - - - - -")
72+
print("File of " + sys.argv[1] + " could not be found.")
73+
print("- - - - - - - - - - - - - - - - -")
74+
75+
for num in sudoko_text:
76+
board.append(int(num))
77+
78+
#split chunks
79+
def chunks(n):
80+
for i in range(0, len(board), n):
81+
yield board[i:i + n]
82+
83+
board = list(chunks(9))
84+
85+
solve()
86+
print_board()

test.txt

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
003020600
2+
900305001
3+
001806400
4+
008102900
5+
700000008
6+
006708200
7+
002609500
8+
800203009
9+
005010300

test2.txt

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
390050000
2+
000200005
3+
000719080
4+
050068000
5+
206003000
6+
000000004
7+
500000000
8+
670105040
9+
109000200

0 commit comments

Comments
 (0)