i have made a simple sudoku solver which is a puzzle game where the player has to figure out the empty cell and checks which numbers are absent from the corresponding row, column.
how can I improve it further?
#include <iostream>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
for (int i = 0; i<9; ++i)
{
if (puzzle[row][i] == num) return 0;
if (puzzle[i][col] == num) return 0;
}
return 1;
}
int solveSudoku(int puzzle[][9], int row, int col)
{
if (row<9 && col<9)
{
if (puzzle[row][col] != 0)
{
if ((col + 1)<9) return solveSudoku(puzzle, row, col + 1);
else if ((row + 1)<9) return solveSudoku(puzzle, row + 1, 0);
else return 1;
}
else
{
for (int i = 0; i<9; ++i)
{
if (isAvailable(puzzle, row, col, i + 1))
{
puzzle[row][col] = i + 1;
if ((col + 1)<9)
{
if (solveSudoku(puzzle, row, col + 1)) return 1;
else puzzle[row][col] = 0;
}
else if ((row + 1)<9)
{
if (solveSudoku(puzzle, row + 1, 0)) return 1;
else puzzle[row][col] = 0;
}
else return 1;
}
}
}
return 0;
}
else return 1;
}
void printSudoku(int puzzle[9][9])
{
for (int i = 0; i<9; ++i)
{
for (int j = 0; j<9; ++j) {
std::cout << puzzle[i][j] << " ";
}
std::cout << "\n";
}
}
int main()
{
int puzzle[9][9] = {
{ 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
solveSudoku(puzzle, 0, 0);
printSudoku(puzzle);
}