Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3,
You should return the followingmatrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路:本题的关键在于,在以螺旋顺序迭代二维数组的时候,如何求出每次迭代的二维数组索引。螺旋顺序为上、右、下、左。本题的解法是,以k代表二维数组的层数,比如以一个4*4的二维数组为例:
1, 2, 3, 4
5, 6, 7, 8
9, 10,11,12
13,14,15,16
第0层的螺旋顺序为:1,2,3,4,8,12,16,15,14,13,9,5。
第1层的螺旋顺序为:6,7,11,10.
代码如下:
int** generateMatrix(intn) { int i, j, k; int index; int **res = calloc(n,sizeof(int *)); int reslen = n * n; for(i = 0; i <n; i++) { res[i] = calloc(n,sizeof(int)); } index = 1; i = j = k = 0; while(index <= reslen) { res[i][j] =index++; if(index > reslen) break; if(i == k) { j++; if(j < n-k)continue; j--; } if(j == n-k-1) { i++; if(i < n-k)continue; i--; } if(i == n-k-1) { j--; if(j >= k) continue; j++; } if(j == k) { i--; if(i == k) { i = j = ++k; } } } return res; }