打印螺旋矩阵

View Code
 1 #include<iostream>
2 #include<iomanip>
3 //#include"CheckMemoryLeak.h"
4
5 using namespace std;
6
7 void spiral(int n)
8 {
9 int temp=0; //记录层数
10 int num=1; //填写数组值
11 int i=0,j=0; //控制循环
12 int x=0,y=-1; //控方向
13 int **N=new int*[n]; //数组
14 for(i=0; i<n; i++)
15 {
16 N[i]=new int[n];
17 }
18 while(temp<=n)
19 {
20 for(i=0; i<n-temp; i++)
21 {
22 N[x][++y]=num++;
23 }
24 if(temp++,temp==n)
25 break;
26 for(i=0;i<n-temp;i++)
27 {
28 N[++x][y]=num++;
29 }
30 for(i=0;i<n-temp;i++)
31 {
32 N[x][--y]=num++;
33 }
34 if(temp++,temp==n)
35 break;
36 for(i=0; i<n-temp; i++)
37 {
38 N[--x][y]=num++;
39 }
40 }
41 for(i=0; i<n; i++)
42 {
43 for(j=0; j<n; j++)
44 {
45 cout<<setw(3)<<N[i][j];
46 }
47 cout<<endl;
48 }
49 for(i=0;i<n;i++)
50 {
51 delete[]N[i];
52 }
53 delete[]N;
54 }
55 int main()
56 {
57 //EnableMemLeakCheck();
58 int n=0;
59 cout<<"请输入整数N的值:"<<endl;
60 cin>>n;
61 spiral(n);
62 return 0;
63 }

运行结果:

Please input  N

5

输出:
   1    2    3    4   5
 16  17  18  19   6
 15  24  25  20   7
 14  23  22  21   8
 13  12  11  10   9

原文地址:https://www.cnblogs.com/landy126/p/1979220.html