forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSudoku Solver.cpp
76 lines (70 loc) · 1.83 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
#include <iostream>
using namespace std;
bool is_valid(int board[9][9], int row, int col, int n) {
for(int i=0;i<9;i++){
if(board[i][col] == n){
return false;
}
if(board[row][i] == n){
return false;
}
}
int sr = (row / 3) * 3;
int sc = (col / 3) * 3;
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (board[sr + r][sc + c] == n) {
return false;
}
}
}
return true;
}
bool solve_sudoku(int board[9][9]) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == 0) {
for (int n = 1; n <= 9; n++) {
if (is_valid(board, r, c, n)) {
board[r][c] = n;
if (solve_sudoku(board)) {
return true;
}
board[r][c] = 0;
}
}
return false;
}
}
}
return true;
}
void print_board(int board[9][9]) {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
cout << board[r][c] << " ";
}
cout << endl;
}
}
int main() {
int sudoku_board[9][9] = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (solve_sudoku(sudoku_board)) {
cout << "Sudoku Solved Successfully!" << endl;
print_board(sudoku_board);
}
else {
cout << "No Solution Found!" << endl;
}
return 0;
}