April 10th, 2006
Sudoku solver in c programming! ha.. how in the wo…
Sudoku solver in c programming! ha.. how in the world is someone supposed to be able to prgram this after learning for 3 months.
#include
void readGrid(FILE *fp, int grid[9][9]){ int i, j; char ch;
for (i = 0; i { for (j = 0; j { fscanf(fp, “%c”, &ch); grid[i][j] = ch - ‘0′; } fscanf(fp, “%c”, &ch); }}
void printGrid(int grid[9][9]){ int i, j;
for (i = 0; i { for (j = 0; j { if (grid[i][j]) printf(”%i”, grid[i][j]); else printf(”.”); if (j%3 == 2) printf(” “); } if (i%3 == 2) printf(”\n”); printf(”\n”); }}
int possibleDigit(int grid[9][9], int x, int y, int digit){ int i, j;
for (j = 0; j if (grid[x][j] == digit) return 0;
for (i = 0; i if (grid[i][y] == digit) return 0;
for (i = x/3*3; i for (j = y/3*3; j if (grid[i][j] == digit) return 0;
return 1;}
int solveSudoku(int grid[9][9]){ int i, j, k;
for (i = 0; i for (j = 0; j if (!grid[i][j]) // if there is an empty cell at [i,j] { for (k = 1; k if (possibleDigit(grid,i,j,k)) { // set the empty cell to its possible digits one-by-one grid[i][j] = k;
// call the next recursion to fill in the next empty cell // and return 1 if the puzzle is solved if (solveSudoku(grid)) return 1; }
// if all possibleDigits have been tried and failed, // set empty cell back to 0 and return failure to the caller grid[i][j] = 0; return 0; }
// this is the base case where success is returned // when all empty cells have been filled return 1;}
int main(){ FILE *in; int grid[9][9] = {{0}};
in = fopen(”sudoku1.txt”,”r”); if (in == NULL) { printf(”Error reading file\n”); return 1; } else { readGrid(in, grid);
printf(”START STATE\n”); printf(”———–\n”); printGrid(grid);
solveSudoku(grid);
printf(”FINAL STATE\n”); printf(”———–\n”); printGrid(grid);
fclose(in); }
return 0;}
Wah… i throw in the towel already.





