1
+ '''
2
+ Aim: Given a 9*9 sudoku board, in which some entries are filled and others are 0
3
+ (0 indicates that the cell is empty), you need to find out whether the Sudoku
4
+ puzzle can be solved or not i.e. return true or false.
5
+
6
+ '''
7
+
8
+ # checking if move could be made or not
9
+ def isSafeToPut (i ,j ,option ,board ,n ):
10
+ for k in range (n ):
11
+ if board [k ][j ]== option or board [i ][k ]== option :
12
+ return False
13
+
14
+ # finding the dimensions of the 3 X 3 box
15
+ starti = (i // 3 )* 3
16
+ startj = (j // 3 )* 3
17
+
18
+ for p in range (starti ,starti + 3 ):
19
+ for q in range (startj ,startj + 3 ):
20
+ if board [p ][q ]== option :
21
+ return False
22
+
23
+ return True
24
+
25
+ # applying basic rules of the game to find the result
26
+ def sudokuSolver (i ,j ,board ,n ):
27
+ if i == n :
28
+ return True
29
+
30
+ if j == n :
31
+ return sudokuSolver (i + 1 ,0 ,board ,n )
32
+
33
+ if board [i ][j ]!= 0 :
34
+ return sudokuSolver (i ,j + 1 ,board ,n )
35
+
36
+ # checking if it's safe to put a number at a place
37
+ for option in range (1 ,10 ):
38
+ if isSafeToPut (i ,j ,option ,board ,n ):
39
+ board [i ][j ]= option
40
+ canWeMoveFwd = sudokuSolver (i ,j + 1 ,board ,n )
41
+ if canWeMoveFwd is True :
42
+ return True
43
+ board [i ][j ]= 0
44
+
45
+ return False
46
+
47
+ # getting the input
48
+ board = [[ int (ele ) for ele in input ().split () ]for i in range (9 )]
49
+ ans = sudokuSolver (0 ,0 ,board ,9 )
50
+
51
+ # printing out the results
52
+ print (ans )
53
+
54
+ '''
55
+
56
+ Sample Input:
57
+ 9 0 0 0 2 0 7 5 0
58
+ 6 0 0 0 5 0 0 4 0
59
+ 0 2 0 4 0 0 0 1 0
60
+ 2 0 8 0 0 0 0 0 0
61
+ 0 7 0 5 0 9 0 6 0
62
+ 0 0 0 0 0 0 4 0 1
63
+ 0 1 0 0 0 5 0 8 0
64
+ 0 9 0 0 7 0 0 0 4
65
+ 0 8 2 0 4 0 0 0 6
66
+
67
+ Sample Output:
68
+ True
69
+
70
+ Explanation:
71
+ According to the rules of sudoku, this can be solved.
72
+
73
+ COMPLEXITY:
74
+
75
+ Time Complexity = O(9^(N*N))
76
+ Space complexity = O(N)
77
+
78
+ '''
0 commit comments