Type:medium
Given a positive integer n, generate a square matrix filled with elements from 1 to n2in spiral order.
Example:
Input:3Output:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
输入一个数字n,输出n*n的螺旋状数组。
和之前一样,按顺序输出即可。注意如何定义二维数组。
class Solution {
public:
vector
vector
int c = n/2;
int m = 1;
for(int i=0; i for(int j=i; j<=n-1-i; j++){ ret[i][j] = m++; } for(int j=i+1; j<=n-1-i; j++){ ret[j][n-1-i] = m++; } for(int j=n-2-i; j>=i; j--){ ret[n-1-i][j] = m++; } for(int j=n-2-i; j>=i+1; j--){ ret[j][i] = m++; } } if(n%2 == 1) ret[c][c] = m++; return ret; } };