如何用c#语言编写魔方矩阵 16阶以内就行,

来源:学生作业帮助网 编辑:作业帮 时间:2024/11/08 06:30:51

如何用c#语言编写魔方矩阵 16阶以内就行,
如何用c#语言编写魔方矩阵 16阶以内就行,

如何用c#语言编写魔方矩阵 16阶以内就行,
function pjmagic(n)
if mod(n,2)== 1
pjmagicA(n);
return;
elseif mod(n,4)==0
pjmagicB(n);
return;
elseif mod(n,2)==0
pjmagicC(n);
return;
else
return;
end
function pjmagicA(n)
m=pjmagic2(n,1);
disp(m);
function pjmagicB(n)
m=zeros(n);
v=0;
for i=1:n
for j=1:n
v=v+1;
m(i,j)=v;
end
end
num4=n/4;
for nn=1:num4
for mm=1:(num4/2)
sub_mat=m((4*mm-3):(4*mm),(4*nn-3):(4*nn));
diag1=diag(sub_mat);
diag2=diag(fliplr(sub_mat));
for k=1:4
[i,j]=find(m==diag1(k));
temp1=m(i,j);
m(i,j)=m(n+1-i,n+1-j);
m(n+1-i,n+1-j)=temp1;
[ii,jj]=find(m==diag2(k));
temp2=m(ii,jj);
m(ii,jj)=m(n+1-ii,n+1-jj);
m(n+1-ii,n+1-jj)=temp2;
end
end
end
disp(m);
function pjmagicC(n)
v=(n*n)/4;
d1=1;
d2=1+v;
d3=1+2*v;
d4=1+3*v;
m1=pjmagic2(n/2,d1);
m2=pjmagic2(n/2,d2);
m3=pjmagic2(n/2,d3);
m4=pjmagic2(n/2,d4);
m=zeros(n);
m(1:(n/2),1:(n/2))=m1;
m(1:(n/2),(n/2+1):end)=m3;
m((n/2+1):end,1:(n/2))=m4;
m((n/2+1):end,(n/2+1):end)=m2;
t=(n+2)/4;
u=n/2;
num=0;
rows=u:-1:1;
cols=[1:(u+1)/2 (u+1)/2-1:-1:1];
j=0;
for i=1:u
temp=m(rows(i),cols(i));
m(rows(i),cols(i))=m(rows(i)+u,cols(i));
m(rows(i)+u,cols(i))=temp;
end
disp(m);
function [m]=pjmagic2(n,v)
m=zeros(n);
rows=1;
cols=(n+1)/2;
m(rows,cols)=v;
num=1;
while(num