从键盘输入一个整数(1~20)
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
解题:
代码却是写的有点烂,没办法,可能现在局限与现在的思维水平。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<iostream> 2 using namespace std; 3 4 int map[1000][1000]; 5 6 int main() 7 { 8 int n; 9 int len , i , j , hang , lie , Count , temp1 , temp2; 10 while(cin>>n) 11 { 12 Count = 1; 13 len = n; 14 hang = 0; 15 lie = 0; 16 if(n == 1) 17 {cout<<'1'<<endl; continue;} 18 for(;;) 19 { 20 temp1 = lie; 21 if(len == 1) 22 { 23 map[hang][lie] = Count++; 24 } 25 for(i = temp1; i < temp1 + len-1 && Count != n*n+1; i++) //最上层 26 map[hang][i] = Count++; 27 temp2 = hang; 28 for(i = temp2; i < temp2 + len-1&& Count != n*n+1; i++) //最右层 29 map[i][n-lie-1] = Count++; 30 for(i = n - temp2-1; i > temp2&& Count != n*n+1; i--) //最下层 31 map[n-hang-1][i] = Count++; 32 for(i = n - temp2-1; i > temp2 && Count != n*n+1; i--) //左 33 map[i][temp1] = Count++; 34 if(Count == n*n+1) break; 35 hang++; 36 lie++; 37 len -= 2; 38 } 39 for(i = 0; i < n; i++) 40 { 41 for(j = 0; j < n; j++) 42 { 43 printf("%3d" , map[i][j]); 44 if(j != n-1) cout<<' '; 45 } 46 cout<<endl; 47 } 48 } 49 return 0; 50 }