概率法求解三阶幻方[C语言]

#include <stdio.h>
#include <string.h>

int in[9]={1,2,3,4,5,6,7,8,9};
int s[9];
int re[3][3];

int sum(int su[])
{
    int i,re=0;
    for(i=0;su[i];i++)
        re+=su[i];
    return re;
}

int main()
{
    int i,j,k,count=0;
    memset(s,0,sizeof(s));
    int SUM = sum(in);
    if(SUM/9 != (float)SUM/9.0)
    {
        printf("wrong\n");
        return 0;
    }
    for(i=0;i<9;i++)
        for(j=i+1;j<9;j++)
            for(k=j+1;k<9;k++)
            {
                if(in[i]+in[j]+in[k] == (int)SUM/3)
                {
                    s[i]++;
                    s[j]++;
                    s[k]++;
                    count++;
                }
            }
    if(count!=8)
    {
        printf("wrong\n");
        return 0;
    }
    int flag=0;
    for(i=8;i>=0;i--) 
    {
        if(s[i]==4)    re[1][1] = in[i];
        if(s[i]==3 && flag==0) { re[0][0] = in[i]; flag++; }
        else if(s[i]==3 && flag==1) { re[0][2] = in[i]; flag++; }
        else if(s[i]==3 && flag==2) { re[2][0] = in[i]; flag++; }
        else if(s[i]==3 && flag==3) { re[2][2] = in[i]; flag++; }
    }
    if(re[0][0]+re[1][1]+re[2][2]!=(int)SUM/3)
    {
        int tmp;
        tmp = re[0][0];
        re[0][0] = re[2][2];
        re[2][2] = tmp;
    }
    re[0][1] = (int)SUM/3 - re[0][0] - re[0][2];
    re[1][0] = (int)SUM/3 - re[0][0] - re[2][0];
    re[1][2] = (int)SUM/3 - re[2][2] - re[0][2];
    re[2][1] = (int)SUM/3 - re[2][2] - re[2][0];

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            printf("%d ",re[i][j]);
        }
        printf("\n");
    }
    return 0;
}

 

posted @ 2014-07-13 00:42  一只快乐的程序猿[Hui]  阅读(1477)  评论(0编辑  收藏  举报