forked from black-shadows/InterviewBit-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSudoku.cpp
More file actions
98 lines (91 loc) · 1.78 KB
/
Sudoku.cpp
File metadata and controls
98 lines (91 loc) · 1.78 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
97
98
bool isValidForRow(vector<vector<char> > &board,int row,char ch)
{
for(int i=0;i<9;i++)
{
if(board[row][i] == ch)
{
return 0;
}
}
return 1;
}
bool isValidForCol(vector<vector<char> > &board,int col,char ch)
{
for(int i=0;i<9;i++)
{
if(board[i][col] == ch)
{
return 0;
}
}
return 1;
}
bool isValidForGrid(vector<vector<char> > &board,int row,int col,char ch)
{
int I = 3*(row/3);
int J = 3*(col/3);
for(int i=I;i<I+3;i++)
{
for(int j=J;j<J+3;j++)
{
if(board[i][j] == ch)
{
return 0;
}
}
}
return 1;
}
bool getPossible(vector<vector<char> > &board,int row,int col,char ch)
{
if(isValidForRow(board,row,ch)&&isValidForCol(board,col,ch)&&isValidForGrid(board,row,col,ch))
{
return true;
}
return false;
}
bool findUnassigned(vector<vector<char> > &board,int &row,int &col)
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(board[i][j] == '.')
{
row = i;
col = j;
return true;
}
}
}
return false;
}
bool solveToGetSudoku(vector<vector<char> > &board)
{
int row,col;
if(!findUnassigned(board,row,col))
{
return true;
}
char ch[] = {'1','2','3','4','5','6','7','8','9'};
for(int i=0;i<9;i++)
{
if(getPossible(board,row,col,ch[i]))
{
board[row][col] = ch[i];
if(solveToGetSudoku(board))
{
return true;
}
board[row][col] = '.';
}
}
return false;
}
void Solution::solveSudoku(vector<vector<char> > &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
solveToGetSudoku(A);
}