/* SUDOKU SOLVER test version The meaning of this program is to solve suduko's. This program is distrubuted under the GNU GPL. Written by Bjarke Bondo Andersen */ /* For standard functions */ #include #include #include #include /* * Take a pointer to a sudoku array as input. Also input where in the * soduku to start. Return 0 if sudoku is done, else erturn 1. */ int solve(int sudoku[9][9], int x_axis, int y_axis) { int new_sudoku[9][9]={0}; int value, done; memcpy(new_sudoku,sudoku,324); /* 81 * 4 = 324 */ value=sudoku[y_axis][x_axis]; if(value!=0) { if(x_axis<8) x_axis++; else if(y_axis<8) { y_axis++; x_axis=0; } else { printf("\nHere goes the solution:\n\n"); if(!printsudoku(new_sudoku)) { fprintf(stderr,"Error printing solution\n"); exit(1); } exit(0); } return(solve(new_sudoku,x_axis,y_axis)); } do { /* first do */ do { /* second do */ if(++value>9) return(1); } while(checknumber(new_sudoku,x_axis,y_axis,value)); /* second do */ new_sudoku[y_axis][x_axis]=value; if(x_axis<8) x_axis++; else if(y_axis<8) { y_axis++; x_axis=0; } else { printf("\nHere goes the solution:\n\n"); if(!printsudoku(new_sudoku)) { fprintf(stderr,"Error printing solution\n"); exit(1); } exit(0); } if(solve(new_sudoku,x_axis,y_axis)) { done=0; if(x_axis>0) x_axis--; else if(y_axis>0) { y_axis--; x_axis=7; } else return(1); } /* if solve() */ else done=1; } while(!done); /* first do */ return(0); } /* Return 1 if number_to_check is found on row, on line or in cube. Else return 0 */ int checknumber(int sudoku[9][9], int x_cordinat, int y_cordinat, int number_to_check) { int x,y; /* check if number_to_check exists on x_cordinat */ for(x=x_cordinat,y=0;y<8;y++) { if(sudoku[y][x]==number_to_check) { return(1); } } /* check if number_to_check exists on y_cordinat */ for(x=0,y=y_cordinat;x<8;x++) { if(sudoku[y][x]==number_to_check) { return(1); } } /* check if number exists in cube */ x=x_cordinat-x_cordinat%3; y=y_cordinat-y_cordinat%3; while(y Starting here 008 020 100 702 093 506 000 806 234 001 000 859 600 084 300 500 000 062 050 200 013 000 001 905 016 000 000 ====================> Ending here */ int main(int argc, char *argv[]) { int sudoku[9][9]={0}; if(argc!=2) { helpmsg(); exit(1); } if(!readinputfile(sudoku,argv[1])) { fprintf(stderr,"Error loading \"%s\"\n", argv[1]); exit(1); } if(solve(sudoku,0,0)) { printf("%s can not be solved\n", argv[1]); exit(1); } /* The solution is now stored in sudoku */ printf("Here goes the solution:\n"); if(!printsudoku(sudoku)) { fprintf(stderr,"Error printing solution\n"); exit(1); } return(0); }