Skip to content

Commit af13460

Browse files
authored
Merge pull request #164 from surajwakka/patch-2
Create Sudoku_Solver.cpp
2 parents 977dd87 + 7f8712a commit af13460

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Coding/Sudoku_Solver.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
const int N = 9;
7+
8+
bool isValid(vector<vector<char>>& board, int row, int col, char num) {
9+
for (int i = 0; i < N; i++) {
10+
if (board[row][i] == num || board[i][col] == num || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num)
11+
return false;
12+
}
13+
return true;
14+
}
15+
16+
bool solveSudoku(vector<vector<char>>& board) {
17+
for (int row = 0; row < N; row++) {
18+
for (int col = 0; col < N; col++) {
19+
if (board[row][col] == '.') {
20+
for (char num = '1'; num <= '9'; num++) {
21+
if (isValid(board, row, col, num)) {
22+
board[row][col] = num;
23+
if (solveSudoku(board))
24+
return true;
25+
board[row][col] = '.'; // Backtrack
26+
}
27+
}
28+
return false;
29+
}
30+
}
31+
}
32+
return true;
33+
}
34+
35+
int main() {
36+
vector<vector<char>> board(N, vector<char>(N));
37+
// Input the Sudoku board here
38+
// '.' represents empty cells
39+
40+
for (int i = 0; i < N; i++) {
41+
for (int j = 0; j < N; j++) {
42+
cin >> board[i][j];
43+
}
44+
}
45+
46+
if (solveSudoku(board)) {
47+
for (int i = 0; i < N; i++) {
48+
for (int j = 0; j < N; j++) {
49+
cout << board[i][j] << " ";
50+
}
51+
cout << endl;
52+
}
53+
} else {
54+
cout << "No solution exists." << endl;
55+
}
56+
57+
return 0;
58+
}

0 commit comments

Comments
 (0)