File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments