#include <iostream>
using namespace std;
class Sudoku {
private:
static const int SIZE = 9;
int board[SIZE][SIZE];
public:
// Constructor
Sudoku(int initialBoard[SIZE][SIZE]) {
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
board[i][j] = initialBoard[i][j];
}
// Print the Sudoku board
void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
// Check if num can be placed at board[row][col]
bool isSafe(int row, int col, int num) {
// Check row & column
for (int x = 0; x < SIZE; x++) {
if (board[row][x] == num || board[x][col] == num)
return false;
}
// Check 3x3 sub-grid
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 (board[startRow + i][startCol + j] == num)
return false;
return true;
}
// Find empty cell
bool findEmptyCell(int &row, int &col) {
for (row = 0; row < SIZE; row++)
for (col = 0; col < SIZE; col++)
if (board[row][col] == 0)
return true;
return false;
}
// Solve Sudoku using Backtracking
bool solve() {
int row, col;
if (!findEmptyCell(row, col))
return true; // Solved
for (int num = 1; num <= 9; num++) {
if (isSafe(row, col, num)) {
board[row][col] = num;
if (solve())
return true;
board[row][col] = 0; // Backtrack
}
}
return false;
}
};