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 ()
0 commit comments