《leetCode》:Spiral Matrix II
来源:互联网 发布:vt和vi的区别 知乎 编辑:程序博客网 时间:2024/06/06 14:01
题目
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For example,Given n = 3,You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
题目大意:用1~n^2的数字按顺时针方向来填充一个n*n的矩阵。
思路
有了上篇博文的思路,这个题就比较简单了。
都是控制好方向和各个方向上的长度,进行赋值即可实现。
实现代码如下:
/** * Return an array of arrays. * Note: The returned array must be malloced, assume caller calls free(). *///此题比较简单;2015年11月21日20:00:12 int** generateMatrix(int n) { if(n<0){ return NULL; } int row=n; int col=n; //分配一个空间来保存结果 int **result=(int **)malloc(row*sizeof(int *)); if(result==NULL){ exit(EXIT_FAILURE); } for(int j=0;j<row;j++){ result[j]=(int *)malloc(col*sizeof(int)); if(result[j]==NULL){ exit(EXIT_FAILURE); } } //nx数组和ny数组用来控制顺时针打印时,下标的变化 //例如:向右访问时,matrix[y][x]中x每次添加1个单位,y不变;因此nx数组中第一个元素为1,ny数组中第一个元素为0; int nx[4]={1,0,-1,0}; int ny[4]={0,1,0,-1}; int i=0;//用来控制方向,i=0是表示向右,i=1时表示向下,i=2时表示向左,i=3时表示向上 int x=-1; int y=0; int value=1; while(row>0&&col>0){ int k; if(i%2==0){ k=col; row--; } else{ k=row; col--; } while(k>0){ x+=nx[i]; y+=ny[i]; result[y][x]=value; value++; k--; } i=(i+1)%4; } return result; }
测试代码如下:
int main(void){ int n; while(scanf("%d",&n)!=EOF&&n>0){ int **result=generateMatrix(n); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ printf("%d ",result[i][j]); } printf("\n"); } }}
1 0
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- Spiral Matrix II -- LeetCode
- android轮询最佳实践service+AlarmManager+Thread
- byte[]数组和int 之间的转换
- 南大软院大神养成计划--HTML和CSS基础课程(二)
- poj2828 Buy Tickets
- 嵌入式驱动开发详解视频教程
- 《leetCode》:Spiral Matrix II
- Python基础 - from import方法与import方法的区别
- poj2528 Mayor’s posters
- python 列表与元组
- LintCode-剑指Offer-(245)子树
- IO流
- 用递归和非递归两种方式找出所有排列
- PC/SC在android上的移植
- 打开或关闭Mac的隐藏文件的命令