螺旋矩阵--我的实现方法

/*
    -2  -1   0   1   2   3
-2 21  22  23  24  25  26
-1 20  7    8   9   10  27
0  19  6    1   2   11  28
1  18  5    4   3   12 29
2  17  16  15 14 13 30
3  36  35  34 33 32 31
*/

 

以1的位置为坐标(0,0),向右为X轴正方向,向下为Y轴正方向

 

/*
    -2  -1   0   1   2   3
-2 21  22  23  24  25  26
-1 20 7   8   9   10  27
0 19  6   1   2   11  28
1 18 5 4 3 12 29
2 17 16 15 14 13 30
3 36 35 34 33 32 31
*/
#include <iostream>

using namespace std;

int getStorey(int x,int y){
 int a,b;
 a = x>0 ? x : -x+1 ;
 b = y>0 ? y : -y+1 ;
 return a>b?a:b;
}

int getValue(int x,int y){
 int storey = getStorey(x,y);   //第多少层的方形
// cout<<"第"<<storey<<"层的方形"<<endl;
 int qside = 2*storey;//坐标所处的方形的边长的个数
 int qmax = qside*qside;//所处的方形的左下角的数值,即最大值


 int value ;
 if(y==storey){//下边
  value = qmax - (x-(-storey+1));
 }else if(-storey+1==y){//上边
  value = qmax - (3*(2*storey-1))+x-(-storey+1);
 }else if(x==storey){//右边
  value = qmax - (2*(2*storey-1))+y-(-storey+1);
 }else if(-storey+1==x){//左边
  value = qmax - (3*(2*storey-1))-(y-(-storey+1));
 }else {
  cout<<"出错了!"<<endl;
  return -1;
 }
 return value ;
}

int main()
{
/*
 int x,y;
 cout<<"请输入x坐标:"<<endl;
 cin>>x;
 cout<<"请输入y坐标:"<<endl;
 cin>>y;

 int value = getVaue(x,y);
   cout<<"坐标为:("<<x<<","<<y<<")处的值:"<<value<<endl;
*/
 int x1=-4,x2=5;
 int y1=-4,y2=5;
 for(int i=x1;i<=x2;i++){
  for(int j=y1;j<=y2;j++){
   int value = getValue(j,i);
   printf("%5d",value); 
  }
  cout<<endl;
 }


 return 0;
}

 

 

代码
/*
-2 -1 0 1 2 3
-2 21 22 23 24 25 26
-1 20 7 8 9 10 27
0 19 6 1 2 11 28
1 18 5 4 3 12 29
2 17 16 15 14 13 30
3 36 35 34 33 32 31
*/
#include
<iostream>

using namespace std;

int getStorey(int x,int y){
int a,b;
a
= x>0 ? x : -x+1 ;
b
= y>0 ? y : -y+1 ;
return a>b?a:b;
}

int getValue(int x,int y){
int storey = getStorey(x,y); //第多少层的方形
// cout<<"第"<<storey<<"层的方形"<<endl;
int qside = 2*storey;//坐标所处的方形的边长的个数
int qmax = qside*qside;//所处的方形的左下角的数值,即最大值


int value ;
if(y==storey){//下边
value = qmax - (x-(-storey+1));
}
else if(-storey+1==y){//上边
value = qmax - (3*(2*storey-1))+x-(-storey+1);
}
else if(x==storey){//右边
value = qmax - (2*(2*storey-1))+y-(-storey+1);
}
else if(-storey+1==x){//左边
value = qmax - (3*(2*storey-1))-(y-(-storey+1));
}
else {
cout
<<"出错了!"<<endl;
return -1;
}
return value ;
}

int main()
{
/*
int x,y;
cout<<"请输入x坐标:"<<endl;
cin>>x;
cout<<"请输入y坐标:"<<endl;
cin>>y;

int value = getVaue(x,y);
cout<<"坐标为:("<<x<<","<<y<<")处的值:"<<value<<endl;
*/
int x1=-4,x2=5;
int y1=-4,y2=5;
for(int i=x1;i<=x2;i++){
for(int j=y1;j<=y2;j++){
int value = getValue(j,i);
printf(
"%5d",value);
}
cout
<<endl;
}


return 0;
}

 

posted on 2010-12-28 10:16  cv_ml_张欣男  阅读(476)  评论(0编辑  收藏  举报

导航