forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sudoku-Solver.cpp
109 lines (88 loc) · 2.62 KB
/
Sudoku-Solver.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
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
99
100
101
102
103
104
105
106
107
108
/*
* Runtime - 56ms
* Memory - 6.8
* LOGIC - described in functions
*
*/
class Solution {
public:
// to check whether num is valid in that row
bool isRowSafe(vector<vector<char>>& board, int row, char num)
{
for(int col = 0;col<9;col++)
{
if(board[row][col] == num)
return true;
}
return false;
}
// to check whether num is valid in that column
bool isColumnSafe(vector<vector<char>>& board, int col , char num)
{
for(int row = 0; row<9; row++)
{
if(board[row][col] == num)
return true;
}
return false;
}
// to check whether num is valid in that 3*3 matrix grid
bool isBoxSafe(vector<vector<char>>& board, int row1, int col1 , char num)
{
for(int row = 0;row<3;row++)
{
for(int col = 0;col<3;col++)
{
if(board[row1 + row][col1 + col] == num)
return true;
}
}
return false;
}
bool isSafe(vector<vector<char>>& board, int row, int col , char num)
{
return !isRowSafe(board,row,num) && !isColumnSafe(board, col, num) && !isBoxSafe(board, row-row%3,col-col%3,num) && board[row][col] == '.';
}
bool findUnassignedLocation(vector<vector<char>>& board, int &row, int &col)
{
for(row = 0;row<9;row++)
{
for(col = 0;col<9;col++)
{
if(board[row][col] == '.')
return true;
}
}
return false;
}
bool solve(vector<vector<char>>& board)
{
int row,col;
if(!findUnassignedLocation(board, row, col))
return true;
for(char i = '1' ; i<='9';i++)
{
if(isSafe(board,row,col,i))
{
board[row][col] = i;
if(solve(board))
return true;
board[row][col] = '.';
}
}
return false;
}
/* A utility function to print grid */
void printGrid(vector<vector<char>>& board)
{
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++)
cout << board[row][col] << " ";
cout << endl;
}
}
void solveSudoku(vector<vector<char>>& board) {
solve(board);
printGrid(board);
}
};