#include #define TRUE 1 #define FALSE 0 /* box width/height */ #define BOX 3 /* puzzle width/height */ #define DIM (BOX * BOX) /* total number of cells */ #define SIZE (DIM * DIM) /* number of connections per cell */ #define CONNS ((DIM - 1) + (DIM - 1) + (BOX - 1) * (BOX - 1)) typedef char cell_t; static int solve(cell_t *puzzle, int offset); static void build_connections(int idx, cell_t *out); static int can_place(const cell_t *puzzle, int idx, cell_t n); static cell_t connections[SIZE][CONNS]; int main(void) { int i, v; static cell_t puzzle[SIZE]; /* Prepare connection arrays */ for (i = 0; i < SIZE; i++) build_connections(i, connections[i]); /* Read puzzle */ for (i = 0; i < SIZE; i++) { if (!scanf("%d", &v) || v < 0 || v > DIM) return TRUE; puzzle[i] = v; } /* Print puzzle and return 0 if solution found, else return TRUE */ if(solve(puzzle, 0)) { for (i = 0; i < SIZE; i++) { if (i) putchar(' '); putchar(puzzle[i] + '0'); } putchar('\n'); return FALSE; } return TRUE; } static int solve(cell_t *puzzle, int offset) { cell_t n; while (offset < SIZE && puzzle[offset]) offset++; if (offset == SIZE) return TRUE; for (n = 1; n <= DIM; n++) if (can_place(puzzle, offset, n)) { puzzle[offset] = n; if (solve(puzzle, offset + 1)) return TRUE; puzzle[offset] = 0; } return FALSE; } static int can_place(const cell_t *puzzle, int idx, cell_t n) { int i; for (i = 0; i < CONNS; i++) if (puzzle[(int)connections[idx][i]] == n) return FALSE; return TRUE; } static void build_connections(int idx, cell_t *out) { int x, y, ix, iy; x = idx % DIM; y = idx / DIM; for (ix = 0; ix < DIM; ix++) for (iy = 0; iy < DIM; iy++) { if (ix == x && iy == y) continue; if ((ix / BOX == x / BOX && iy / BOX == y / BOX) || ix == x || iy == y) *out++ = ix + iy * DIM; } }