螺旋输出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
#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
相关文章推荐
- 【每日面试题】矩阵的螺旋输出
- Java实现输出回环数(螺旋矩阵)的方法示例
- 矩阵螺旋输出
- JavaScript输出螺旋矩阵
- 螺旋输出N*N矩阵
- (大神勿入)据说是一道面试题,然后自己就写了一发(矩阵的螺旋输出)
- 输出双螺旋矩阵
- 螺旋矩阵赋值或输出
- 矩阵顺时针螺旋输出2种不同的方法。
- [LeetCode] Spiral Matrix 螺旋输出矩阵
- JavaScript定义及输出螺旋矩阵的方法详解
- 矩阵顺时针螺旋输出2种不同的方法。
- 螺旋矩阵--由外向内旋转输出
- 螺旋输出二维矩阵
- [算法]方正面试题:N×N矩阵螺旋打印输出
- 输出螺旋矩阵(二)
- C++编程循环输出螺旋矩阵
- java逆时针螺旋输出矩阵
- C语言输出螺旋矩阵
- 螺旋数字矩阵的输出