forked from abhaygupta08/Hacktober-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sudoku_Solver.cpp
98 lines (92 loc) · 2.24 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
/*
SUDOKU SOLVER
// Time ->O(9^(n*n))
*/
#include <bits/stdc++.h>
using namespace std;
bool check(int mat[9][9], int no, int i, int j)
{
// checking row and column
for (int k = 0; k < 9; k++)
{
if (mat[i][k] == no || mat[k][j] == no)
{
return false;
}
}
// checking 3x3 subgrid
int si = i - i % 3;
int sj = j - j % 3;
for (int i = si; i < si + 3; i++)
{
for (int j = sj; j < sj + 3; j++)
{
if (mat[i][j] == no)
{
return false;
}
}
}
return true;
}
bool solve(int matrix[9][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (matrix[i][j] == 0)
{
for (int no = 1; no <= 9; no++)
{
if (check(matrix, no, i, j))
{
matrix[i][j] = no;
if (solve(matrix) == true)
return true;
else
matrix[i][j] = 0;
}
}
return false;
}
}
}
return true;
}
bool isItSudoku(int matrix[9][9])
{
// Write your code here.
if (solve(matrix) == true)
{
return true;
}
return false;
}
void printGrid(vector<vector<int>> &grid)
{
for (int row = 0; row < grid.size(); row++)
{
for (int col = 0; col < grid.size(); col++)
cout << grid[row][col] << " ";
cout << endl;
}
}
int main()
{
vector<vector<int>> grid{{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
// printGrid(grid);
if (solve(grid) == true)
printGrid(grid);
else
cout << "No solution exists";
return 0;
}