LeeCode-Spiral Matrix II
2016-04-25 19:00
387 查看
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 ] ]
/*** Return an array of arrays.* Note: The returned array must be malloced, assume caller calls free().*/int** generateMatrix(int n) {int **Maxtrix;Maxtrix=(int **)malloc(n*sizeof(int*));for(int k=0;k<n;k++)Maxtrix[k]=(int *)malloc(sizeof(int)*n);int number = 1;int top = 0;int bottom = n-1;int left = 0;int right = n-1;int i,j;while(number<=n*n){for(i=left;i<=right;i++)Maxtrix[top][i]=number++;top++;for(i=top;i<=bottom;i++)Maxtrix[i][right]=number++;right--;for(i=right;i>=left;i--)Maxtrix[bottom][i]=number++;bottom--;for(i=bottom;i>=top;i--)Maxtrix[i][left]=number++;left++;}return Maxtrix;}
相关文章推荐
- 表单
- c语言 按格式读取文件内容
- Word无法打开该文件,因为文件格式与文件扩展名不匹配的解决办法
- MySQL中information_schema数据库相关权限的说明
- java的hashcode
- solr入门之solr安全控制的研究和实践(一)
- VS中如何添加lib,dll
- docker-machine的基本使用
- LeeCode-Remove Element
- log4j.properties 从jar中抽身
- ØMQ -入门教程(序)
- ThreadLocal知识介绍
- Xib 约束 UIScrollerView
- Python标准库06 子进程 (subprocess包)
- DOS BAT中用echo显示一些保留字符
- 对正则表达式的一些汇总
- LeeCode-Sort Colors
- bnu 51640 Training Plan(类似区间dp)(北师16校赛)
- Lightoj-1428 Melody Comparison(kmp&&后缀数组)
- POJ2154 Polya+欧拉函数