LeeCode-Spiral Matrix II

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 }
原文地址:https://www.cnblogs.com/vpoet/p/4660520.html