Hi all, first and probably only post -- I was on a plane from LA to Seattle and found a "diabolical" sudoku in the LA paper someone left behind. Since I didn't solve it on the plane (sleep took over ;-)), I decided to write a program to solve it for me.
So I have included here a freeware C language recursive program for anywone who wants to play with it. Just don't take credit for it (like homework, or school project) because you didn't write it.
Regards,
Wim
-----------------------------------------------------------
/* freeware, simple recursive sudoku solver */
/* it will print all possible solutions */
/* inspired by a hard sudoku found in the */
/* #if 0 ... */
/* wim colgate, January, 11th, 2006 */
#define BASE(num) ((num/9)*9)
#define TOP(num) ((num%9))
#define ULEFT(num) (((BASE(num)/27)*27)+(((num-BASE(num))/3)*3))
typedef struct _sudoku {
unsigned char array[81];
} sudoku;
int solution_found = 0;
#if 0
sudoku original_board = {
0, 0, 7, 0, 6, 0, 0, 1, 0,
5, 0, 0, 2, 0, 0, 0, 8, 7,
9, 0, 0, 1, 0, 0, 0, 3, 0,
0, 0, 0, 3, 0, 0, 7, 4, 0,
0, 5, 0, 0, 0, 0, 0, 9, 0,
0, 9, 8, 0, 0, 2, 0, 0, 0,
0, 7, 0, 0, 0, 1, 0, 0, 9,
2, 1, 0, 0, 0, 8, 0, 0, 4,
0, 8, 0, 0, 5, 0, 3, 0, 0
};
#else
sudoku original_board = {
3, 0, 0, 0, 4, 9, 0, 0, 0,
0, 0, 0, 7, 0, 0, 0, 6, 0,
0, 7, 2, 0, 0, 0, 0, 8, 0,
5, 0, 0, 0, 8, 0, 0, 0, 2,
0, 0, 4, 5, 0, 3, 6, 0, 0,
6, 0, 0, 0, 2, 0, 0, 0, 3,
0, 9, 0, 0, 0, 0, 5, 3, 0,
0, 4, 0, 0, 0, 5, 0, 0, 0,
0, 0, 0, 4, 1, 0, 0, 0, 7
};
#endif
int place_next(int loc, sudoku *pboard)
{
while ((loc < 81) && (pboard->array[loc] != 0)) loc++;
if (loc <81) return loc;
return -1;
}
void print_solution(sudoku *pboard)
{
int i, j;
if (solution_found) printf("-------------------------------------\n\n");
for (i=0; i<9; i++) {
for (j=0; j<9; j++) {
if (j%3 == 0) printf(" ");
printf(" %d", pboard->array[i*9+j]);
}
if (i==2 || i == 5) printf("\n");
printf("\n");
}
printf("\n");
solution_found = 1;
}
int row_check(int loc, int val, sudoku *pboard)
{
int i = BASE(loc);
int j;
for (j=0; j<9; j++) {
if (pboard->array[i+j] == val) return 0;
}
return 1;
}
int column_check(int loc, int val, sudoku *pboard)
{
int i = TOP(loc);
int j;
for (j=0; j<9; j++) {
if (pboard->array[i+j*9] == val) return 0;
}
return 1;
}
int square_check(int loc, int val, sudoku *pboard)
{
int i = ULEFT(loc);
int j, k;
for (j=0; j<3; j++) {
for (k=0; k<3; k++) {
if (pboard->array[i+j*9+k] == val) return 0;
}
}
return 1;
}
int sudo(int loc, int num, sudoku board)
{
if (num > 9) return -1;
loc = place_next(loc, &board);
if (loc == -1) {
print_solution(&board);
return -1;
}
if (row_check(loc, num, &board) && column_check(loc, num, &board) && square_check(loc, num, &board)) {
board.array[loc] = num;
sudo(loc+1, 1, board);
board.array[loc] = 0;
sudo(loc, num+1, board);
} else {
sudo(loc, num+1, board);
}
}
main(int argc, char *argv[])
{
sudo(0, 1, original_board);
if (!solution_found) printf("no solution found\n");
}