I need a Sudoku game solver in C programming (Not C++). Standard 9 by 9. It need
ID: 3819854 • Letter: I
Question
I need a Sudoku game solver in C programming (Not C++). Standard 9 by 9. It needs to request the user for the setup (known and unknowns) using 0s, or spaces or dots for the unknowns. After all 9x9 constants and variables have been input by the user, it will print the 9 by 9 result (in a nice squared drawn box if possible). Super thank u very much in advance for you kind help.
It will look something like this.
Please enter layout using "0" for unknowns/variables:
100060002
000400000
000000006
000000200
000300006
000100200
020008000
000030000
005001000
One possible solution is:
9 4 6 9 4 3 6 3 5
7 3 6 9 4 8 5 2 5
6 2 6 7 8 9 3 2 6
4 9 7 6 5 1 3 5 9
1 3 7 4 2 6 9 1 4
4 3 4 6 9 4 3 1 6
6 4 1 2 9 6 4 2 8
6 3 2 7 6 4 6 3 5
7 5 4 1 9 7 5 3 5
Explanation / Answer
#include <stdio.h>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
int rowStart = (row/3) * 3;
int colStart = (col/3) * 3;
int i, j;
for(i=0; i<9; ++i)
{
if (puzzle[row][i] == num) return 0;
if (puzzle[i][col] == num) return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num) return 0;
}
return 1;
}
int fillSudoku(int puzzle[][9], int row, int col)
{
int i;
if(row<9 && col<9)
{
if(puzzle[row][col] != 0)
{
if((col+1)<9) return fillSudoku(puzzle, row, col+1);
else if((row+1)<9) return fillSudoku(puzzle, row+1, 0);
else return 1;
}
else
{
for(i=0; i<9; ++i)
{
if(isAvailable(puzzle, row, col, i+1))
{
puzzle[row][col] = i+1;
if((col+1)<9)
{
if(fillSudoku(puzzle, row, col +1)) return 1;
else puzzle[row][col] = 0;
}
else if((row+1)<9)
{
if(fillSudoku(puzzle, row+1, 0)) return 1;
else puzzle[row][col] = 0;
}
else return 1;
}
}
}
return 0;
}
else return 1;
}
int main()
{
int i, j;
int puzzle[9][9]={{0, 0, 0, 3, 0, 0, 0, 9, 0},
{1, 9, 0, 4, 7, 0, 6, 0, 8},
{0, 5, 2, 8, 1, 9, 4, 0, 7},
{2, 0, 0, 0, 4, 8, 0, 0, 0},
{0, 0, 9, 0, 0, 0, 5, 0, 0},
{0, 0, 0, 7, 5, 0, 0, 0, 9},
{9, 0, 7, 3, 6, 4, 1, 8, 0},
{5, 0, 6, 0, 8, 1, 0, 7, 4},
{0, 8, 0, 0, 0, 0, 0, 0, 0}};
if(fillSudoku(puzzle, 0, 0))
{
printf(" +-----+-----+-----+ ");
for(i=1; i<10; ++i)
{
for(j=1; j<10; ++j) printf("|%d", puzzle[i-1][j-1]);
printf("| ");
if (i%3 == 0) printf("+-----+-----+-----+ ");
}
}
else printf(" NO SOLUTION ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.