File tree 1 file changed +116
-0
lines changed
1 file changed +116
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://practice.geeksforgeeks.org/problems/solve-the-sudoku-1587115621/1
2
+
3
+ class Solution
4
+ {
5
+ public:
6
+
7
+ bool check (int grid[N][N],int x, int y, int k)
8
+ {
9
+ int col,row;
10
+ for (col = 0 ; col<=8 ; col++)
11
+ {
12
+ if (grid[x][col]==k)
13
+ return false ;
14
+ }
15
+ for (row = 0 ; row<=8 ; row++)
16
+ {
17
+ if (grid[row][y]==k)
18
+ return false ;
19
+ }
20
+ if (x<=2 )
21
+ row = 0 ;
22
+ else if (x<=5 )
23
+ row = 3 ;
24
+ else
25
+ row = 6 ;
26
+
27
+ if (y<=2 )
28
+ col = 0 ;
29
+ else if (y<=5 )
30
+ col = 3 ;
31
+ else
32
+ col = 6 ;
33
+
34
+ for (int i = row; i < (row+3 ); i++)
35
+ {
36
+ for (int j = col; j< (col+3 ); j++)
37
+ {
38
+ if (grid[i][j]==k)
39
+ return false ;
40
+ }
41
+ }
42
+
43
+ return true ;
44
+ }
45
+
46
+ bool solve (int grid[N][N], int x, int y)
47
+ {
48
+ if (x==N-1 && y==N-1 )
49
+ {
50
+ if (grid[x][y]==0 )
51
+ {
52
+ for (int i = 1 ; i<10 ; i++)
53
+ {
54
+ if (check (grid,x,y,i))
55
+ {
56
+ grid[x][y]=i;
57
+ return true ;
58
+
59
+ }
60
+ }
61
+ return false ;
62
+ }
63
+ return true ;
64
+ }
65
+
66
+ int next_row,next_col;
67
+ if (y==N-1 )
68
+ {
69
+ next_row = x+1 ;
70
+ next_col = 0 ;
71
+ }
72
+ else
73
+ {
74
+ next_row = x;
75
+ next_col = y+1 ;
76
+ }
77
+
78
+ if (grid[x][y]!=0 )
79
+ {
80
+ return solve (grid,next_row,next_col);
81
+ }
82
+ else
83
+ {
84
+ for (int i = 1 ; i<10 ; i++)
85
+ {
86
+ if (check (grid,x,y,i))
87
+ {
88
+ grid[x][y] = i;
89
+ bool res = solve (grid,next_row,next_col);
90
+ if (res==true )
91
+ return true ;
92
+ grid[x][y] = 0 ;
93
+ }
94
+ }
95
+ return false ;
96
+ }
97
+ }
98
+
99
+ bool SolveSudoku (int grid[N][N])
100
+ {
101
+ return solve (grid,0 ,0 );
102
+ }
103
+
104
+
105
+ void printGrid (int grid[N][N])
106
+ {
107
+ int i,j;
108
+ for (i=0 ; i<N; i++)
109
+ {
110
+ for (j=0 ; j<N; j++)
111
+ {
112
+ cout << grid[i][j] << " " ;
113
+ }
114
+ }
115
+ }
116
+ };
You can’t perform that action at this time.
0 commit comments