历届试题 九宫幻方

#include 
#include 
const int MAXN=10;
int graph[MAXN],vis[MAXN],ans[MAXN];
int flag=0;
bool isok()
{
        int sum=graph[1]+graph[2]+graph[3];
        for(int i=4;i<=9;i+=3)
                if((graph[i]+graph[i+1]+graph[i+2])!=sum)
                        return false;
        for(int i=1;i<=3;i++)
                if((graph[i]+graph[i+3]+graph[i+6])!=sum)
                return false;
        if((graph[1]+graph[5]+graph[9])!=sum||(graph[3]+graph[5]+graph[7])!=sum)
                return false;
        return true;
}
 
void dfs(int pos)
{
        if(pos==10&&isok())
        {
                flag++;
                if(flag==1)
                        memcpy(ans,graph,sizeof(graph));
                return;
        }
        if(graph[pos])
                dfs(pos+1);
        else
                for(int i=1;i<=9;i++)
                {
                        if(vis[i])
                                continue;
                        vis[i]=1;
                        graph[pos]=i;
                        dfs(pos+1);
                        vis[i]=0;
                        graph[pos]=0;
                }
}
int main()
{
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=9;i++)
        {
                scanf("%d",&graph[i]);
                vis[graph[i]]=1;
        }
        dfs(1);
        if(flag==1)
                for(int i=1;i<=9;i++)
                      printf("%d%c", ans[i], (i%3==0)? '\n' : ' ');
        else if(flag>1)
                printf("Too Many\n");
        return 0;
}

https://blog.csdn.net/h_hui_hui/article/details/79499183

你可能感兴趣的:(蓝桥)