#include
#include
#include
int main( int argc, char * argv[] )
{
int pos = 0;
int row,col;
int val;
int a[9][9] = {0};
int count;
srand(time(NULL));
pos = 0;
LOOP_OUT:
while(pos<=80) //pos 0 ==> a[0][0], pos 80 ==> a[8][8]
{
row = pos/9;
col = pos%9;
val = random()%9 + 1;
for(count = 1; count<= 9; count++)
{
if( check_ok(a,pos,val) )
{
a[row][col] = val;
pos++;
goto LOOP_OUT;
}
else //if val is 5, we try 6,7,8,9,1,2,3,4
val = val%9+1;
}
// this pos , val failed
if(pos >=9)
pos -=9; //pos fail, back 1 line
}
//print result
for( row = 0; row<9; row++)
{
for( col = 0; col<9; col++)
printf("%d ", a[row][col]);
printf("\n");
}
return 0;
}
int check_ok(int a[9][9], int pos, int value)
{
int row = pos/9;
int col = pos%9;
int i,j;
j = col;
for( i=row-1; i>=0;i--)
{
if( a[i][j] == value )
return 0;
}
i = row;
for( j=col-1; j>=0; j--)
{
if( a[i][j] == value )
return 0;
}
return 1;
}
1 5 2 3 6 8 7 4 9
4 6 9 7 8 1 2 3 5
2 8 1 4 9 3 5 6 7
8 2 3 5 4 6 9 7 1
9 7 4 6 1 5 8 2 3
3 9 5 1 7 2 4 8 6
5 3 8 9 2 7 6 1 4
6 1 7 8 5 4 3 9 2
7 4 6 2 3 9 1 5 8