-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsudokuSolver.cpp
More file actions
101 lines (94 loc) · 2.32 KB
/
sudokuSolver.cpp
File metadata and controls
101 lines (94 loc) · 2.32 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<bits/stdc++.h>
using namespace std;
#define UNASSIGNED 0
#define N 9
class Sudoku{
int grid[N][N]={
{3, 0, 6, 0, 0, 8, 4, 0, 0},
{0, 8, 0, 0, 1, 0, 7, 2, 0},
{2, 0, 0, 0, 4, 0, 0, 0, 9},
{5, 0, 7, 0, 0, 9, 0, 1, 0},
{0, 0, 0, 0, 3, 0, 0, 9, 0},
{0, 3, 0, 0, 5, 0, 2, 0, 7},
{1, 0, 8, 0, 0, 4, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 4, 8},
{9, 2, 0, 1, 0, 7, 3, 0, 0}
};
public:
void setGrid();
void printGrid();
bool usedInRow(int row,int num);
bool usedInCol(int col,int num);
bool usedInBox(int boxRow,int boxCol,int num);
bool isSafe(int row,int col,int num);
bool findUnassignedLocation(int &row,int &col);
bool solveSudoku();
};
void Sudoku::printGrid(){
for(int row=0;row<N;row++){
for(int col=0;col<N;col++){
cout<<grid[row][col]<<" ";
if((col+1)%3==0)
cout<<" ";
}
cout<<"\n";
if((row+1)%3==0)
cout<<"\n";
}
}
bool Sudoku::usedInRow(int row, int num){
for(int col=0;col<N;col++)
if(grid[row][col]==num)
return true;
return false;
}
bool Sudoku::usedInCol(int col,int num){
for(int row=0;row<N;row++)
if(grid[row][col]==num)
return true;
return false;
}
bool Sudoku::usedInBox(int boxRow,int boxCol,int num){
for(int row=0;row<3;row++)
for(int col=0;col<3;col++)
if(grid[boxRow+row][boxCol+col]==num)
return true;
return false;
}
bool Sudoku::isSafe(int row,int col,int num){
return ( !usedInRow(row,num)&&
!usedInCol(col,num)&&
!usedInBox(row-row%3,col-col%3,num)&&
grid[row][col]==UNASSIGNED
);
}
bool Sudoku::findUnassignedLocation(int &row,int &col){
for(row=0;row<N;row++)
for(col=0;col<N;col++)
if(grid[row][col]==UNASSIGNED)
return true;
return false;
}
bool Sudoku::solveSudoku(){
int row,col;
if(!findUnassignedLocation(row,col))
return true;
//cout<<row<<" "<<col<<"\n";
for(int num=1;num<=9;num++){
if(isSafe(row,col,num)){
grid[row][col]=num;
if(solveSudoku())
return true;
grid[row][col]=UNASSIGNED;
}
}
return false;
}
int main(){
Sudoku s;
if(s.solveSudoku()==true)
s.printGrid();
else
cout<<"\nNo Solution Exists!";
return 0;
}