Sei sulla pagina 1di 8

Problem 1 of 1729

Answer : 42
I went straightaway for the brute force approach. I
first found a c program to print all the permutations of
a given set of numbers from:

http://c-program-example.com/2012/05/c-program-to-
print-all-the-possible-permutations-of-given-
digits.html

Then, i created a 3-d array of dimensions [362880][3]


[3], which is basically 9! 3x3 matries. I played around
with the above code (permutation’s one) till i stored
each output in the array. Thus, now i had all possible
3x3 matrices with the numbers 1 to 9, so i checked if a
given matrix satisfied the question conditions, and
incremented my count by 1 if they did. Lastly, i
printed count.

This is my code:-

#include <stdio.h>
#include<stdlib.h>

void visit(int k);


int permutation();
int lev=-1,n,val[50],a[50];
int arr[362880][3][3];

int main()
{
int x, y, z, count=0,flag;
permutation();

for(x=0;x<362880;x++)
{
for(y=0;y<3;y++)
{
for(z=0;z<3;z++)
{
if(y>0 && z>0)
{
if(arr[x][y][z]>arr[x][y-1][z] &&
arr[x][y][z]>arr[x][y][z-1])
{
flag=1;
}
else
{
flag=0;
break;
}
}
else if(y==0 && z!=0)
{
if(arr[x][y][z]>arr[x][y][z-1])
{
flag=1;
}
else
{
flag=0;
break;
}
}

else if(z==0 && y!=0)


{
if(arr[x][y][z]>arr[x][y-1][z])
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
if(flag==0)
{
break;
}
}
if(flag==1)
{
count++;
}
}

printf("\n%d\n", count);

int permutation()
{
int i,j;
printf("\nEnter how many numbers: ");
scanf("%d",&n);
printf("\nEnter %d numbers: ",n);
for(i=0;i<n;i++)
{
val[i]=0;
j=i+1;
scanf("%dnn",&a[j]);
}
visit(0);
getchar();
return 0;
}

void visit(int k)
{
int i,b,c;
static int d=0;
val[k]=++lev;
if(lev==n)
{
for(i=0;i<n;i++)
{
if(i==0)
{
b=0;
c=0;
arr[d][b][c]=a[val[i]];
}
else if(i==1)
{
b=0;
c=1;
arr[d][b][c]=a[val[i]];
}
else if(i==2)
{
b=0;
c=2;
arr[d][b][c]=a[val[i]];
}
else if(i==3)
{
b=1;
c=0;
arr[d][b][c]=a[val[i]];
}
else if(i==4)
{
b=1;
c=1;
arr[d][b][c]=a[val[i]];
}
else if(i==5)
{
b=1;
c=2;
arr[d][b][c]=a[val[i]];
}
else if(i==6)
{
b=2;
c=0;
arr[d][b][c]=a[val[i]];
}
else if(i==7)
{
b=2;
c=1;
arr[d][b][c]=a[val[i]];
}
else if(i==8)
{
b=2;
c=2;
arr[d][b][c]=a[val[i]];
}

}
d++;
}
for(i=0;i<n;i++)
if(val[i]==0)
visit(i);
lev--;
val[k]=0;

}
***

Potrebbero piacerti anche