Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- const int Nmax=630;
- int a[Nmax];
- int n;
- int lastK;
- int Nhap();
- int Xuat();
- int xuatfile();
- int Try(int i);
- int isOK(int i, int x);
- int findLastK();
- int main()
- {
- printf("Nhap so lieu de bai...\n");
- Nhap();
- lastK = findLastK();
- printf("De bai:\n");
- Xuat();
- //xuatfile();
- printf("\nBam enter de bat dau giai...\n");
- getchar();
- Try(0);
- getchar();
- return 0;
- }
- int Nhap()
- {
- int i, tmp;
- FILE *fp = NULL;
- fp = fopen("input.txt", "r");
- fscanf(fp,"%d",&n);
- for (i=0; i<n*n*n*n; i++)
- {
- fscanf(fp, "%d", &tmp);
- a[i]= tmp;
- }
- fclose(fp);
- return 0;
- }
- int Xuat()
- {
- int i;
- for (i=0; i<n*n*n*n; i++)
- {
- if ( i%(n*n) ==0) printf("\n");
- printf(" %d", a[i]);
- }
- printf("\n------------------");
- return 0;
- }
- int xuatfile()
- {
- int i;
- FILE *fp;
- fp=fopen("output.txt","w");
- for (i=0; i<n*n*n*n; i++)
- {
- if ( i == n*n*n*n) printf("\n----------------------");
- if(i%(n*n)==0)
- {
- printf("\n");
- fprintf(fp,"\n");
- }
- printf(" %d", a[i]);
- fprintf(fp,"%d ", a[i]);
- }
- fclose(fp);
- }
- int Try(int i)
- {
- int x;
- while (a[i]!=0)
- i++;
- for (x=1; x<=n*n; x++)
- if (isOK(i, x))
- {
- a[i] = x;
- if (i==lastK){
- xuatfile();
- printf("\n");
- }
- else
- Try(i+1);
- a[i] = 0;
- }
- return 0;
- }
- int isOK(int i, int x)
- {
- int k, t, t1, t2;
- int kth, ktc, kto;
- int tmpX, tmpY;
- //kiem tra hang thu i da co cai nao trung chua
- t1= i%(n*n);
- t2= i/(n*n);
- for (k=(t2*n*n); k<(t2*n*n+n*n); k++)
- if (a[k] == x)
- return 0;
- //kiem tra cot thu j da co cai nao trung chua
- for (k=0; k<n*n; k++)
- if (a[k*n*n+t1] == x)
- return 0;
- //kiem tra trong o 3x3
- tmpX = t2%n; tmpY = t1%n;
- for (k=t2-tmpX; k<=t2-tmpX+n-1; k++)
- for (t=t1-tmpY; t<=t1-tmpY+n-1; t++)
- if (a[k*n*n+t] == x)
- return 0;
- return 1;
- }
- int findLastK()
- {
- int i;
- for (i=n*n*n*n-1; i>=0;i--)
- if (a[i]==0)
- {
- return (i);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement