#include <stdio.h> #include <stdlib.h> #define OFF 0 #define ON 1 #define OK 0 #define NG -1 #define N0 0 #define N3 3 #define N9 9 #define N20 20 #define NN 100 typedef struct { int x; int y; } XY; typedef struct { int f1[N9]; int kakutei; XY xy[N20]; } BAN; BAN a1[N9][N9]; void disp(void) { int x , y; int i; printf("----------\n"); for(y = N0 ; y < N9 ; y++) { for(x = N0 ; x < N9 ; x++) { for(i = N0 ; i < N9 ; i++) { if(a1[y][x].f1[i] == ON) printf("%d" , i + 1); } if(x < 8) printf("-"); } printf("\n"); } } int init(char *filename) { FILE *fpi; char buf[NN]; int x , y; int x1 , y1; int x2 , y2; int i; int n; for(y = N0 ; y < N9 ; y++) { for(x = N0 ; x < N9 ; x++) { for(i = N0 ; i < N9 ; i++) a1[y][x].f1[i] = ON; a1[y][x].kakutei = -1; n = N0; for(y2 = N0 ; y2 < N9 ; y2++) { if(y != y2) { a1[y][x].xy[n].x = x; a1[y][x].xy[n++].y = y2; } } for(x2 = N0 ; x2 < N9 ; x2++) { if(x != x2) { a1[y][x].xy[n].x = x2; a1[y][x].xy[n++].y = y; } } x1 = (x / N3) * N3; y1 = (y / N3) * N3; for(y2 = N0 ; y2 < N3 ; y2++) { for(x2 = N0 ; x2 < N3 ; x2++) { if( x1 + x2 != x && y1 + y2 != y) { a1[y][x].xy[n].x = x1 + x2; a1[y][x].xy[n++].y = y1 + y2; } } } } } fpi = fopen(filename , "r"); if(fpi == NULL) { fprintf(stderr , "Can't open %s\n" , filename); return(NG); } for(y = N0 ; y < N9 ; y++) { fgets(buf , NN , fpi); for(x = N0 ; x < N9 ; x++) { if(buf[x] != ' ') { n = buf[x] - '1'; for(i = N0 ; i < N20 ; i++) a1[a1[y][x].xy[i].y][a1[y][x].xy[i].x].f1[n] = OFF; for(i = N0 ; i < N9 ; i++) { if(i != n) a1[y][x].f1[i] = OFF; } } } } fclose(fpi); return(OK); } int shokyo(void) { int x , y; int i; int n; int cnt = N0; int ib; for(y = N0 ; y < N9 ; y++) { for(x = N0 ; x < N9 ; x++) { if(a1[y][x].kakutei != -1) continue; n = N0; for(i = N0 ; i < N9 ; i++) { if(a1[y][x].f1[i] == ON) { ib = i; n++; if(n > 1) break; } } if(n == 1) { for(i = N0 ; i < N20 ; i++) { a1[a1[y][x].xy[i].y][a1[y][x].xy[i].x].f1[ib] = OFF; } a1[y][x].kakutei = ib; cnt++; } } } return(cnt); } void soatari(int x , int y) { int i , j; int x2 , y2; int tf1[9]; int tf2[20]; if(y == N9) { disp(); return; } x2 = x + 1; y2 = y; if(x2 == N9) { x2 = N0; y2++; } if(a1[y][x].kakutei != -1) { soatari(x2 , y2); return; } for(i = N0 ; i < N9 ; i++) { if(a1[y][x].f1[i] == OFF) continue; for(j = N0 ; j < N9 ; j++) { tf1[j] = a1[y][x].f1[j]; if(i != j) a1[y][x].f1[j] = OFF; } for(j = N0 ; j < N20 ; j++) { tf2[j] = a1[a1[y][x].xy[j].y][a1[y][x].xy[j].x].f1[i]; a1[a1[y][x].xy[j].y][a1[y][x].xy[j].x].f1[i] = OFF; } soatari(x2 , y2); for(j = N0 ; j < N20 ; j++) { a1[a1[y][x].xy[j].y][a1[y][x].xy[j].x].f1[i] = tf2[j]; } for(j = N0 ; j < N9 ; j++) { a1[y][x].f1[j] = tf1[j]; } } } int main(int argc , char **argv) { int cnt; if(argc != 2) { fprintf(stderr , "Usage : %s filename\n" , argv[0]); return(EXIT_FAILURE); } if(init(argv[1]) == NG) { return(EXIT_FAILURE); } cnt = shokyo(); while(cnt > 0) cnt = shokyo(); disp(); soatari(0 , 0); return(EXIT_SUCCESS); } |