-
Notifications
You must be signed in to change notification settings - Fork 1
/
057_Valid Sudoku.cpp
46 lines (40 loc) · 1.03 KB
/
057_Valid Sudoku.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
// Time complexity -> O(9 ^ K)
// Space complexity -> O(K)
bool isSafe(int row, int col, int curr, int matrix[9][9])
{
for(int i = 0; i < 9; ++i)
{
if(matrix[i][col] == curr)
return false;
if(matrix[row][i] == curr)
return false;
if(matrix[3*(row/3) + i/3][3*(col/3) + i%3] == curr)
return false;
}
return true;
}
bool isItSudoku(int matrix[9][9]) {
// Write your code here.
for(int i = 0; i < 9; ++i)
{
for(int j = 0; j < 9; ++j)
{
if(matrix[i][j] == 0)
{
for(int k = 1; k <= 9; ++k)
{
if(isSafe(i, j, k, matrix))
{
matrix[i][j] = k;
if(isItSudoku(matrix))
return true;
else
matrix[i][j] = 0;
}
}
return false;
}
}
}
return true;
}