File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ def find_empty (board ):
2+ for i in range (len (board )):
3+ for j in range (len (board [0 ])):
4+ if board [i ][j ] == 0 :
5+ return (i , j )
6+ return None
7+
8+ def valid (board , num , pos ):
9+ for i in range (len (board [0 ])):
10+ if board [pos [0 ]][i ] == num and pos [1 ] != i :
11+ return False
12+
13+ for i in range (len (board )):
14+ if board [i ][pos [1 ]] == num and pos [0 ] != i :
15+ return False
16+
17+ box_x = pos [1 ] // 3
18+ box_y = pos [0 ] // 3
19+
20+ for i in range (box_y * 3 , box_y * 3 + 3 ):
21+ for j in range (box_x * 3 , box_x * 3 + 3 ):
22+ if board [i ][j ] == num and (i ,j ) != pos :
23+ return False
24+ return True
25+
26+ def solve (board ):
27+ find = find_empty (board )
28+ if not find :
29+ return True
30+ else :
31+ row , col = find
32+
33+ for i in range (1 ,10 ):
34+ if valid (board , i , (row , col )):
35+ board [row ][col ] = i
36+
37+ if solve (board ):
38+ return True
39+
40+ board [row ][col ] = 0
41+
42+ return False
43+
44+ def print_board (board ):
45+ for i in range (len (board )):
46+ if i % 3 == 0 and i != 0 :
47+ print ("- - - - - - - - - - - -" )
48+ for j in range (len (board [0 ])):
49+ if j % 3 == 0 and j != 0 :
50+ print ("|" , end = " " )
51+ if j == 8 :
52+ print (board [i ][j ])
53+ else :
54+ print (str (board [i ][j ]) + " " , end = "" )
55+
56+
57+ board = [
58+ [7 ,8 ,0 ,4 ,0 ,0 ,1 ,2 ,0 ],
59+ [6 ,0 ,0 ,0 ,7 ,5 ,0 ,0 ,9 ],
60+ [0 ,0 ,0 ,6 ,0 ,1 ,0 ,7 ,8 ],
61+ [0 ,0 ,7 ,0 ,4 ,0 ,2 ,6 ,0 ],
62+ [0 ,0 ,1 ,0 ,5 ,0 ,9 ,3 ,0 ],
63+ [9 ,0 ,4 ,0 ,6 ,0 ,0 ,0 ,5 ],
64+ [0 ,7 ,0 ,3 ,0 ,0 ,0 ,1 ,2 ],
65+ [1 ,2 ,0 ,0 ,0 ,7 ,4 ,0 ,0 ],
66+ [0 ,4 ,9 ,2 ,0 ,6 ,0 ,0 ,7 ]
67+ ]
68+ print ("Original Sudoku Board:" )
69+ print_board (board )
70+ solve (board )
71+ print ("\n Solved Sudoku Board:" )
72+ print_board (board )
You can’t perform that action at this time.
0 commit comments