题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> a(n, vector<int>(n));
int x1 = 0, x2 = n - 1, y1 = 0, y2 = n - 1;
int k = 1;
while (x1 <= x2 && y1 <= y2) {
for(int j = y1; j <= y2; j++)
a[x1][j] = k++;
for (int i = x1 + 1; i <= x2; i++)
a[i][y2] = k++;
if (x2 != x1) {
for (int j = y2 - 1; j >= y1; j--)
a[x2][j] = k++;
}
if (y2 != y1) {
for (int i = x2 - 1; i >= x1 + 1; i--)
a[i][y1] = k++;
}
x1++, y1++, x2--, y2--;
}
return a;
}
};