forked from freyxfi/AllInHacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudoko.cpp
106 lines (78 loc) · 2.05 KB
/
Sudoko.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
#include <iostream>
#include <vector>
using namespace std;
const int N = 9;
void printSudoku(const vector<vector<int>>& grid) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
}
bool isSafe(vector<vector<int>>& grid, int row, int col, int num) {
for (int i = 0; i < N; i++) {
if (grid[row][i] == num) {
return false;
}
}
for (int i = 0; i < N; i++) {
if (grid[i][col] == num) {
return false;
}
}
int startRow = row - (row % 3);
int startCol = col - (col % 3);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[startRow + i][startCol + j] == num) {
return false;
}
}
}
return true;
}
bool solveSudoku(vector<vector<int>>& grid) {
int row, col;
bool foundEmpty = false;
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
if (grid[row][col] == 0) {
foundEmpty = true;
break;
}
}
if (foundEmpty) {
break;
}
}
if (!foundEmpty) {
return true;
}
for (int num = 1; num <= 9; num++) {
if (isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (solveSudoku(grid)) {
return true;
}
grid[row][col] = 0;
}
}
return false;
}
int main() {
vector<vector<int>> sudokuGrid(N, vector<int>(N, 0));
cout << "Enter the Sudoku puzzle (0 for empty cells, separate digits with spaces):" << endl;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> sudokuGrid[i][j];
}
}
if (solveSudoku(sudokuGrid)) {
cout << "Solved Sudoku:" << endl;
printSudoku(sudokuGrid);
} else {
cout << "No solution exists for the given Sudoku puzzle." << endl;
}
return 0;
}