1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
|
#include <stdio.h>
#include <stdlib.h>
struct t_cell
{
char val; //value
char col; //column
char row; //row
char sub; //submatrix
} grid[81];
typedef struct t_cell cell;
void init_grid(cell *grid);
void fill_grid(cell *grid, FILE *stream);
int valid_row(cell *grid, int row);
int valid_col(cell *grid, int col);
int valid_sub(cell *grid, int sub);
inline int valid_cell(cell *grid, int pos);
#warning TODO: Program uses recursion. Complex puzzles may crash.
int solve_grid(cell *grid, int pos);
int main()
{
int i = 0, j = 0;
puts("Initializing grid constants...");
init_grid(grid);
puts("Done.\n");
puts("Please type the 81 numbers of the sudoku board.\n"
"Use a dash or 0 as unknown. "
"Extraneous characters are ignored.\n");
fill_grid(grid, stdin);
//3---8--765692-7-3-4-83-621--1-6349----4-25-6--8-7--3247-2-4-6---9657314-1--962---
puts("\nSolution: ");
for(; i < 10000; i++)
{
solve_grid(grid, i < 81 ? i : i % 81);
for(j = 0; j < 81; j++) printf("%d", grid[j].val);
puts("\n");
}
for(i = 0; i < 81; i++) printf("%d", grid[i].val);
return 0;
}
int solve_grid(cell *grid, int pos)
{
int i = 0;
if(pos == 81) return 1;
if(grid[i].val != 0)
return valid_cell(grid, pos) && solve_grid(grid, pos + 1);
for(; i < 9; i++)
{
grid[i].val = i + 1;
if(valid_cell(grid, pos) && solve_grid(grid, pos + 1)) return 1;
}
if(pos != 0) grid[pos].val = 0;
return 0;
}
void init_grid(cell *grid)
{
int i = 0;
for(; i < 81; i++)
{
grid[i].row = (int)i/9;
grid[i].col = (int)i%9;
grid[i].sub = (int)(grid[i].row/3)*3+(grid[i].col/3);
}
}
void fill_grid(cell *grid, FILE *stream)
{
char s;
int i = 0;
for(; i < 80; i++)
{
s = fgetc(stream);
if((s < '0' || s > '9') && s != '-') {i--; continue;}
if(s == '-') grid[i].val = 0;
else grid[i].val = s - '0';
}
}
int valid_row(cell *grid, int row)
{
int total = 0, i = 0;
for(; i < 81; i++)
if(grid[i].row == row) total += grid[i].val;
return total == 45;
}
int valid_col(cell *grid, int col)
{
int total = 0, i = 0;
for(; i < 81; i++)
if(grid[i].col == col) total += grid[i].val;
return total == 45;
}
int valid_sub(cell *grid, int sub)
{
int total = 0, i = 0;
for(; i < 81; i++)
if(grid[i].sub == sub) total += grid[i].val;
return total == 45;
}
inline int valid_cell(cell *grid, int pos)
{
return valid_row(grid, grid[pos].row) &&
valid_col(grid, grid[pos].col) &&
valid_sub(grid, grid[pos].sub);
}
|