Created
December 13, 2019 22:09
-
-
Save yves-chevallier/690604b595d0946c77e57f7b2278932e to your computer and use it in GitHub Desktop.
Sudoku Solver (brute force)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define BLOCK (3) | |
#define WIDTH (BLOCK * BLOCK) | |
#if WIDTH % BLOCK > 0 | |
# error "Invalid block size" | |
#endif | |
bool read(int grid[WIDTH][WIDTH], FILE *fp) | |
{ | |
for (size_t k = 0; k < WIDTH * WIDTH; k++) { | |
int *cell = &grid[k / WIDTH][k % WIDTH]; | |
if (fscanf(fp, "%d", cell) != 1 || *cell < 0 || *cell > WIDTH) { | |
return 1; | |
} | |
} | |
return 0; | |
} | |
void display(int grid[WIDTH][WIDTH]) | |
{ | |
for (size_t row = 0; row < WIDTH; row++) { | |
for (int col = 0; col < WIDTH; col++, putchar(' ')) { | |
printf("%d", grid[row][col]); | |
} | |
putchar('\n'); | |
} | |
} | |
bool is_legal(int grid[WIDTH][WIDTH], int row, int col, int val) | |
{ | |
bool res = true; | |
for (size_t i = 0, k = 0; i < BLOCK; i++) { | |
for (size_t j = 0; j < BLOCK; j++, k++) { | |
res &= grid[row][k] != val; | |
res &= grid[k][col] != val; | |
res &= grid[row - row % BLOCK + i][col - col % BLOCK + j] != val; | |
} | |
} | |
return res; | |
} | |
int level = 0; | |
bool solve(int grid[WIDTH][WIDTH], int pos) | |
{ | |
printf("%*d\n", level * 3, pos); | |
level++; | |
if (pos == WIDTH * WIDTH) { | |
level--; | |
return true; | |
} | |
size_t row = pos / WIDTH, col = pos % WIDTH; | |
if (grid[row][col] != 0) { | |
bool u = solve(grid, pos + 1); | |
level--; | |
return u; | |
} | |
for (size_t val = 1; val <= WIDTH; val++) { | |
if (is_legal(grid, row, col, val)) { | |
grid[row][col] = val; | |
if (solve(grid, pos + 1)) { | |
level--; | |
return true; | |
} | |
} | |
} | |
grid[row][col] = 0; | |
level--; | |
return false; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int grid[WIDTH][WIDTH] = {0}; | |
if (!(argc > 1 && strcmp("-0", argv[1]) == 0)) { | |
if (read(grid, stdin)) { | |
fprintf(stderr, "Error while reading!\n"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
solve(grid, 0); | |
display(grid); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment