您的位置:首页 > 其它

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;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: