您的位置:首页 > 其它

螺旋输出N*N矩阵

2007-04-24 10:06 447 查看
#include <iostream>
#include <iomanip>
using namespace std;
void func(int n){
static const int dir[][2]={{0,1},{1,0},{0,-1},{-1,0}};
const int size=n+2;
int **ver=new int *[size];
for (int i=0;i<size;++i)
{
ver[i]=new int[size];
if (i==0||i==size-1)
{
memset(ver[i],-1,size*sizeof(int));
}
else{
memset(ver[i],0,size*sizeof(int));
ver[i][0]=-1;
ver[i][size-1]=-1;
}
}
int iIndex=0;
int max=n*n;
int cnt=1;
int i=1,j=1;
while (cnt<=max)
{
while (ver[i][j]==0)
{
ver[i][j]=cnt;
i+=dir[iIndex][0];
j+=dir[iIndex][1];
++cnt;
}
i-=dir[iIndex][0];
j-=dir[iIndex][1];
if (cnt>max)
{
break;
}
iIndex=(iIndex+1)%4;
i+=dir[iIndex][0];
j+=dir[iIndex][1];
while (ver[i][j]!=0)
{
iIndex=(iIndex+1)%4;
i+=dir[iIndex][0];
j+=dir[iIndex][1];
}
}

for (int i=1;i<size-1;++i)
{
for (int j=1;j<size-1;++j)
{
cout<<setw(6)<<ver[i][j];
}
cout<<endl;
}
}
int main(){
int n;
cin>>n;
func(n);
}

10
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: