看不懂这个代码 求下面题的思路,

budetcbc007 2010-05-04 10:56:14
在9(3*3)个方格的方阵中填入数字1到N(N>=10)内的某9个数字每个方格填一个整数,要求相邻两个方格的两个整数之和为质数。 试求所有的解
看不懂这个代码 求下面题的思路,

/*
在9(3*3)个方格的方阵中填入数字1到N(N>=10)内的某9个数字每个方格填一个整数,
要求相邻两个方格的两个整数之和为质数。 试求所有的解
*/

#include<stdio.h>
#define N 12

void write(int a[])
{int i,j;
for(i=0;i<3;i++){

for(j=0;j<3;j++)
printf("%3d",a[3*i+j]);
printf("\n");
}
scanf("% * c");
}


int b[N+1];
int a[10];
int isPrime(int m)
{
int i;
int primes[]={2,3,5,7,11,13,17,19,23,29,-1};

if(m==1||m%2==0) return 0;
for(i=0;primes[i]>0;i++)
if(m==primes[i]) return 1;

for(i=3;i*i<=m;){
if(m%i==0) return 0;
i+=2;
}
return 1;
}

int checkMatrix[][3]={
{-1},{0,-1},{1,-1},
{0,-1},{1,3,-1},{2,4,-1},
{3,-1},{4,6,-1},
{5,7,-1}};

int selectNum(int start)
{
int j;
for(j=start;j<=N;j++)
if(b[j]) return j;
return 0;
}

int check(int pos)
{
int i,j;
if(pos<0) return 0;
for(i=0;(j=checkMatrix[pos][i])>=0;i++)
if(!isPrime(a[pos]+a[i])) return 0;
return 1;
}

int extend(int pos)
{
a[++pos]=selectNum(1);
b[a[pos]]=0;
return pos;
}

int change(int pos)
{
int j;

while(pos>=0 && (j=selectNum(a[pos]+1))==0)
b[a[pos--]]=1;
if(pos<0) return -1;

b[a[pos]]=1;
a[pos]=j;
b[j]=0;

return pos;
}

void find()
{
int ok=1,pos=0;
a[pos]=1;
b[a[pos]]=0;
do
{
if(ok)
if(pos==8){
write(a);
pos=change(pos);
}

else pos=extend(pos);
else pos=change(pos);
ok=check(pos);
}while(pos>=0);
}

void main(){

int i;
for(i=1;i<=N;i++)
b[i]=1;
find();

}

...全文
183 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
KG071 2010-05-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 mf0606 的回复:]
呵呵,貌似是C语言……
[/Quote]

应该是C语言
wss_scaler 2010-05-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 mf0606 的回复:]
呵呵,貌似是C语言……
[/Quote]
肯定是C
mf0606 2010-05-08
  • 打赏
  • 举报
回复
呵呵,貌似是C语言……
budetcbc007 2010-05-08
  • 打赏
  • 举报
回复
在高程的书上看到了这个道题,
不太懂,又没有注释
budetcbc007 2010-05-08
  • 打赏
  • 举报
回复
看不到图片啊!!
hardycheng 2010-05-05
  • 打赏
  • 举报
回复
图片显示的不全,http://imgsrc.baidu.com/baike/pic/item/58af236d8987f6e8431694b5.jpg

这个就是图片地址
hardycheng 2010-05-05
  • 打赏
  • 举报
回复
最小的质数是2


看看这个算法

keeya0416 2010-05-05
  • 打赏
  • 举报
回复
看的头痛

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧