-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudokuSolver.cpp
More file actions
74 lines (69 loc) · 1.26 KB
/
SudokuSolver.cpp
File metadata and controls
74 lines (69 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Sudoku Solver
#include<iostream>
#include<cmath>
using namespace std;
bool canPlace(int mat[][9], int i ,int j, int n ,int number){
for(int x=0;x<n;x++){
if(mat[x][j]==number || mat[i][x]==number){
return false;
}
}
int rn = sqrt(n);
int sx = (i/rn)*rn;
int sy = (j/rn)*rn;
for(int x=sx;x<sx+rn;x++){
for(int y=sy;y<sy+rn;y++){
if(mat[x][y]==number){
return false;
}
}
}
return true;
}
bool SolveSudoku(int mat[][9],int i,int j,int n){
// base case
if(i==n){
// print the sudoku
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
return true;
}
if(j==n){
return SolveSudoku(mat,i+1,0,n);
}
if(mat[i][j]!=0){
return SolveSudoku(mat,i,j+1,n);
}
// recursive case
for(int number=1;number<=n;number++){
if(canPlace(mat,i,j,n,number)){
mat[i][j] = number;
bool couldWeSolve = SolveSudoku(mat,i,j+1,n);
if(couldWeSolve==true){
return true;
}
}
}
mat[i][j] = 0;
return false;
}
int main(){
int mat[][9] =
{
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}
};
SolveSudoku(mat,0,0,9);
return 0;
}