螺旋矩阵
2013-11-21 10:58
323 查看
下面是一个5×5的螺旋方阵,试编程打印出此形式的n×n(n<10)阶的方阵。
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
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
#include<stdio.h> #define N 5 //螺旋矩阵 int main() { int count,i,j; int direction=1; //分为左、下、上、右四个方向用1,2,3,4代替 int array ={0}; i=0; j=0; for(count=1;count<=N*N;count++) { array[i][j]=count; //确定下一个方向 if(direction==1) { if (j==N-1 || array[i][j+1]!=0) direction=2; }else { if (direction==2) { if (i==N-1 || array[i+1][j]!=0) direction=3; }else { if(direction==3) { if (j==0 || array[i][j-1]!=0) direction=4; }else { if (i==0 || array[i-1][j]!=0) direction=1; } } } //根据方向决定下一个坐标 switch(direction) { case 1: j++; break; case 2: i++; break; case 3: j--; break; case 4: i--; break; } } //输出 for(i=0;i<N;i++) { for(j=0;j<N;j++) printf("%3d", array[i][j]); printf("\n"); } return 1; }
相关文章推荐
- LintCode-剑指Offer-(374)螺旋矩阵
- 螺旋矩阵
- java 实现螺旋矩阵
- 脑洞脑洞 螺旋矩阵
- 模拟【p2239】 螺旋矩阵
- 45.螺旋矩阵 (5分)
- 从键盘输入一个整数(1~20) 则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。
- 螺旋矩阵赋值或输出
- 矩阵顺时针螺旋赋值
- [C++]LeetCode: 110 Spiral Matrix (螺旋输出矩阵元素)
- NOIP 2014 普及组 T3 螺旋矩阵
- 飘逸的python - 打印螺旋矩阵
- 螺旋矩阵——正逆序
- 螺旋输出N*N矩阵
- 由内向外的螺旋矩阵
- 螺旋矩阵
- 螺旋矩阵
- 1050. 螺旋矩阵(25)
- PAT (Basic Level) Practise (中文)1050. 螺旋矩阵(25)
- 螺旋矩阵问题