码迷,mamicode.com
首页 > 其他好文 > 详细

LeeCode-Spiral Matrix II

时间:2015-07-20 10:30:20      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

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 /**
 2  * Return an array of arrays.
 3  * Note: The returned array must be malloced, assume caller calls free().
 4  */
 5 int** generateMatrix(int n) {
 6         int **Maxtrix;
 7     
 8     Maxtrix=(int **)malloc(n*sizeof(int*));
 9     for(int k=0;k<n;k++)
10         Maxtrix[k]=(int *)malloc(sizeof(int)*n);
11 
12     int number = 1;
13     int top = 0;
14     int bottom = n-1;
15     int left = 0;
16     int right = n-1;
17 
18     int i,j;
19     while(number<=n*n)
20     {
21         for(i=left;i<=right;i++)
22             Maxtrix[top][i]=number++;
23         top++;
24 
25         for(i=top;i<=bottom;i++)
26             Maxtrix[i][right]=number++;
27         right--;
28 
29         for(i=right;i>=left;i--)
30             Maxtrix[bottom][i]=number++;
31         bottom--;
32 
33         for(i=bottom;i>=top;i--)
34             Maxtrix[i][left]=number++;
35         left++;
36 
37     }
38     return Maxtrix;
39 }

 

LeeCode-Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/vpoet/p/4660520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!