学习总结一

有一个3*3方格,每个位置只能填写1~9,不能重复填写,要求:横向相加、竖向相加、斜向相加的值相等。
在想这道题的过程中,我一开始在想不通过随机置换数字来通过做出这道题,我通过一维数组来做这道题,我想的是一开始就摆好123456789这些数字,然后通过交换数字来找到目标数组,我刚开始在想的时候没想出这个的逻辑关系,后来就先用随机置换的方式。

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

char ppp ();
int h[10]={0,1,2,3,4,5,6,7,8,9};


int main()
{
  int a,b,c=0;
  //char p=false;
  while(ppp()==false)
    {
	  srand((unsigned)time(NULL));
      a=rand()%9+1;
	  b=rand()%9+1;
      c=h[a];
	  h[a]=h[b];
	  h[b]=c;
	  printf("%d  %d\n",a,b);
    }
		                 for(int i=1;i<4;i++)
						 {
						   for (int j=1;j<4;j++)
							   printf("%d" ,h[j+3*(i-1)]);
                           printf("\n");
					      }
}

char ppp()
{
   if (h[1]+h[2]+h[3]==h[1]+h[4]+h[7]  &&  h[1]+h[2]+h[3]==h[1]+h[5]+h[9]  &&  h[1]+h[2]+h[3]==h[3]+h[6]+h[9]  &&  h[1]+h[2]+h[3]==h[2]+h[5]+h[8]  &&  h[1]+h[2]+h[3]==h[4]+h[5]+h[6]  &&  h[1]+h[2]+h[3]==h[7]+h[8]+h[9]  &&  h[1]+h[2]+h[3]==h[3]+h[5]+h[7])
	  return true;
	 else return false;
}

这个是我刚开始的时候做出来的成果,但是出现了一个问题,这个程序因为我学习的浅,运行的非常慢,在1秒内置换的都是相同的位置,所以我后来还是在想老的方式,在翻之前的课本以及查询相关资料后,初步学习了全排列,做出了以下程序

#include<stdio.h>
int a[10];
int out[10];
int n;
int main()
{
    void quanpl(int);
	scanf("%d",&n);
	quanpl(0);
	return 0;
}

 
 
 
void quanpl(int num)
{
    void print();
	int i;
	if(num==n)
		print();
	else
	{
		for(i=0;i<=n-1;i++)
		{
			if(!a[i])
			{
				a[i]=1;
				out[num]=i+1;
				quanpl(num+1);
				a[i]=0;
			}
		}
	}
}
 
 
void print()
{
	if (out[0]+out[3]+out[6]==out[0]+out[1]+out[2] && out[0]+out[4]+out[8]==out[0]+out[1]+out[2] && out[1]+out[4]+out[7]==out[0]+out[1]+out[2]  &&  out[2]+out[5]+out[8]==out[0]+out[1]+out[2]  &&  out[6]+out[7]+out[8]==out[0]+out[1]+out[2]  &&  out[2]+out[4]+out[6]==out[0]+out[1]+out[2]  &&  out[3]+out[4]+out[5]==out[0]+out[1]+out[2])
	{
	for(int i=0;i<=n-1;i++)
		printf("%d ",out[i]);
	printf("\n");
    }
}

这个程序的大致框架来自

https://blog.csdn.net/saber_jk/article/details/79968661

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值