-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSudoku.cpp
66 lines (57 loc) · 1.69 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
bool isValid(vector<vector<int>>& board, int row, int col, int val)
{
for (int i = 0; i < 9; i++) {
if (board[i][col] == val)
return false;
if (board[row][i] == val)
return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == val) //Checking corresponding 3x3 grid within the same loop
return false;
}
return true;
}
bool solveSudoku(vector<vector<int>>& board)
{
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == 0) {
for (int val = 1; val <= 9; val++) {
if (isValid(board, i, j, val)) {
board[i][j] = val;
if (solveSudoku(board))
return true;
else
board[i][j] = 0;
}
}
return false;
}
}
}
return true;
}
int main()
{
vector<vector<int>> board = { { 3, 0, 0, 0, 0, 1, 0, 0, 2 },
{ 2, 0, 1, 0, 3, 0, 6, 0, 4 },
{ 0, 0, 0, 2, 0, 4, 0, 0, 0 },
{ 8, 0, 9, 0, 0, 0, 1, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 0, 5, 0 },
{ 7, 0, 2, 0, 0, 0, 4, 0, 9 },
{ 0, 0, 0, 5, 0, 9, 0, 0, 0 },
{ 9, 0, 4, 0, 8, 0, 7, 0, 5 },
{ 6, 0, 0, 1, 0, 7, 0, 0, 3 } };
if (solveSudoku(board)) {
cout << "Solution : \n";
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
return 0;
}