-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathSudokuSolver.cpp
72 lines (66 loc) · 1.59 KB
/
SudokuSolver.cpp
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
#include<bits/stdc++.h>
using namespace std;
bool isValid(vector<vector<char>> board,int po,int i,int j){
char c='0'+po;
for(int m=0;m<board.size();m++){
if(board[i][m]==(c))
return false;
}
for(int m=0;m<board.size();m++){
if(board[m][j]==(c))
return false;
}
int sub_i=3*(i/3);
int sub_j=3*(j/3);
for(int m=0;m<3;m++){
for(int n=0;n<3;n++){
if(board[sub_i+m][sub_j+n]==(c))
return false;
}
}
return true;
}
// solving the sudoku solver using backtracking
bool solve (vector<vector<char>> &board,int i,int j){
int ni,nj;
// end of board
if(i==board.size()){
return true;
}
// end of row , switch to new row
if(j==(board[0].size()-1)){
ni=i+1;nj=0;
} // if the row has not ended then simply just increment the value of the column
else{
nj=j+1;ni=i;
}
// backtracking
if(board[i][j]=='0'){
for(int po=1;po<=9;po++){
if(isValid(board,po,i,j)){
char c='0'+po;
board[i][j]=c;
if(solve(board,ni,nj))
return true;
board[i][j]='0';
}
}
}
else
{
if(solve(board,ni,nj))
return true;
}
return false;
}
int main() {
int ni=0,nj=0;//ni=next i,nj=next j
solve(board,ni,nj);
cout<<"\n\n\nThe solved sudoku is : \n\n\n";
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
}