int sudoku(unsigned int numbers_def[16]) { clear_window(); unsigned int numbers[16]; for (int i = 0; i < 16; i++) { numbers[i] = numbers_def[i]; } char option = 'a'; for (int i = 0; option != EXIT;) { print_sudoku(numbers, i); option = getchar(); if (option == FIX) { clear_window(); if (checkSudoku(numbers)) { printf("\n\t\t\t\tYou win!\n"); } else { printf("\n\t\t\t\tYou lost\n"); } printf("\t\t\t\tPress any key to exit\n"); getchar(); return 0; } else if (option == UP && i >= 4) { i -= 4; } else if (option == DOWN && i <= 11) { i += 4; } else if (option == LEFT && i > 0) { i--; } else if (option == RIGHT && i < 15) { i++; } else if (option >= '1' && option <= '4' && numbers_def[i] == 0) { numbers[i] = (option - '0'); } else if (option == NEW) { return 1; } } return 0; }
/* Input: An empty queue, and an initialized sudoku s, an empty queue * for the solutions, and a pointer to a variable to store the * number of guesses * Returns: NULL if no possible solutions exist or the queue is not * empty, and otherwise the solution to the input puzzle. * ----------------------------------------------------------- * Solves the puzzle using backtracking. The solver is initialized by * putting the puzzle into the empty queue. Then, each iteration will * pull a board out of the queue, perform a simple reduction on that * board, and then make a guess on the cell which has the least number * of possibilities. If verbose is set, it prints each board before * making a guess, giving a sense of the whole solution process. * * If there is nothing to pull out of the queue, there are no possible * solutions to the puzzle, and the function returns an error value of * NULL. If the queue is not empty at initialization, the function * prints an error message regardless of the state of the flags, and * returns an error. */ sudoku solve(queue q, sudoku s, int * guesses) { if (!isEmptyQueue(q)) { printf("Error: call to solve with a non-empty queue"); return NULL; } putQueue(q, (void *) s); *guesses = 0; int slvd = 0; while (1) { if (getQueue(q, (void **) &s)){ return NULL; } reduce(s); if(verbose) { system("clear"); printSudoku(s, pretty); printf("\n"); } slvd = checkSudoku(s); if (slvd == -1) deleteSudoku(s); else if (slvd == 1) return s; else { if(guess(q, s)) { printf("Error: Full queue"); return NULL; } deleteSudoku(s); (*guesses)++; } } }