1
+ def print_grid (arr ):
2
+ for i in range (9 ):
3
+ for j in range (9 ):
4
+ print (arr [i ][j ], end = " " )
5
+ print ()
6
+
7
+ def find_empty_location (arr , l ):
8
+ for row in range (9 ):
9
+ for col in range (9 ):
10
+ if arr [row ][col ] == 0 :
11
+ l [0 ] = row
12
+ l [1 ] = col
13
+ return True
14
+ return False
15
+
16
+ def used_in_row (arr , row , num ):
17
+ for i in range (9 ):
18
+ if (arr [row ][i ] == num ):
19
+ return True
20
+ return False
21
+
22
+ def used_in_col (arr , col , num ):
23
+ for i in range (9 ):
24
+ if (arr [i ][col ] == num ):
25
+ return True
26
+ return False
27
+
28
+ def used_in_box (arr , row , col , num ):
29
+ for i in range (3 ):
30
+ for j in range (3 ):
31
+ if (arr [i + row ][j + col ] == num ):
32
+ return True
33
+ return False
34
+
35
+ def check_location_is_safe (arr , row , col , num ):
36
+ return not used_in_row (arr , row , num ) and not used_in_col (arr , col , num ) and not used_in_box (arr , row - row % 3 , col - col % 3 , num )
37
+
38
+
39
+ def solve_sudoku (arr ):
40
+
41
+ l = [0 , 0 ]
42
+
43
+ if (not find_empty_location (arr , l )):
44
+ return True
45
+
46
+ row = l [0 ]
47
+ col = l [1 ]
48
+
49
+ for num in range (1 , 10 ):
50
+
51
+ if (check_location_is_safe (arr , row , col , num )):
52
+ arr [row ][col ] = num
53
+
54
+ if (solve_sudoku (arr )):
55
+ return True
56
+
57
+ arr [row ][col ] = 0
58
+
59
+ return False
60
+
61
+
62
+ if __name__ == "__main__" :
63
+
64
+ # creating a 2D array for the grid
65
+ grid = [[0 for x in range (9 )]for y in range (9 )]
66
+
67
+ grid = [[3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 ],
68
+ [5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ],
69
+ [0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 ],
70
+ [0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 ],
71
+ [9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 ],
72
+ [0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 ],
73
+ [1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 ],
74
+ [0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 ],
75
+ [0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 ]]
76
+
77
+
78
+ if (solve_sudoku (grid )):
79
+ print_grid (grid )
80
+ else :
81
+ print ("No solution exists" )
0 commit comments