Skip to content

Instantly share code, notes, and snippets.

@eloidrai
Last active March 7, 2023 07:44
Show Gist options
  • Save eloidrai/7c7c9dbe8ae9abfbc044e1884f93e1bf to your computer and use it in GitHub Desktop.
Save eloidrai/7c7c9dbe8ae9abfbc044e1884f93e1bf to your computer and use it in GitHub Desktop.
Solveur de sudoku par backtracking
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int grille[81] = {0};
void init (FILE * file, int * grille) {
for (int i = 0; i<81; i++) {
char c = fgetc(file);
if (c == '\n') c = fgetc(file);
if (c != ' ') grille[i] = (int)c - 48;
}
}
void print(int * grille) {
for (int j = 0; j<9; j++) {
for (int i = 0; i<9; i++) {
printf("%d", grille[9 * j + i]);
}
printf("\n");
}
}
bool check(int * grille, int i, int j) {
// Check lines
for (int ci=0; ci<9; ci++) {
if (ci == i) continue;
if (grille[9 * j + ci] == grille[9 * j + i]) return false;
}
// Check columns
for (int cj=0; cj<9; cj++) {
if (cj == j) continue;
if (grille[9 * cj + i] == grille[9 * j + i]) return false;
}
// Check square
int row = j/3;
int col = i/3;
for (int cj=3*row; cj<3*(row+1); cj++) { // Parcours vertical de la ligne du carré
for (int ci=3*col; ci<3*(col+1); ci++) { // Parcours horizontal de la colonne du carré
if (cj == j && ci == i) continue;
if (grille[9 * cj + ci] == grille[9 * j + i]) return false;
}
}
return true;
}
int next_available(int * grille, int i, int j) {
int c = 8*j + i;
while (c < 81 && grille[c] != 0) c++;
return c;
}
void solve(int * grille, int ii, int ij) {
int next = next_available(grille, ii, ij);
int i = next % 9;
int j = next / 9;
if (next==81) {
printf("Trouvé !\n");
return print(grille);
}
for (int n = 1; n<=9; n++) {
grille[9 * j + i] = n;
if (check(grille, i, j)) {
solve(grille, i, j);
}
}
grille[9 * j + i] = 0;
}
int main (int argc, char ** argv) {
if (argc < 2) {
printf("Please specify a file !\n");
return EXIT_FAILURE;
}
FILE * file = fopen(argv[1], "r");
init(file, grille);
check(grille, 0, 5);
solve(grille, 0, 0);
fclose(file);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment