#include <stdio.h>
#include <stdbool.h>
#define N 9
// Check if num can be placed at board[row][col]
bool isSafe(int board[N][N], int row, int col, int num) {
for (int x = 0; x < N; x++) {
if (board[row][x] == num) return false; // check row
if (board[x][col] == num) return false; // check column
}
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; // check box
}
}
return true;
}
// Recursive function to solve Sudoku using backtracking
bool solveSudoku(int board[N][N]) {
for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
if (board[row][col] == 0) { // empty cell found
for (int num = 1; num <= 9; num++) {
if (isSafe(board, row, col, num)) {
board[row][col] = num; // place num
if (solveSudoku(board)) return true; // recurse
board[row][col] = 0; // backtrack
}
}
return false; // no valid number found
}
}
}
return true; // solved
}
// Print the Sudoku board
void printBoard(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int main() {
int board[N][N] = {
{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 (solveSudoku(board)) {
printBoard(board);
} else {
printf("No solution exists\n");
}
return 0;
}