思路:
和Spiral Matrix I思路一模一样, 请参考http://blog.csdn.net/hiimdaosui/article/details/52035391
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (! n) return res;
int count = 0, direction = 0;
int left = 0, top = 0, right = n - 1, bot = n - 1;
int row = 0, col = 0;
while (count++ < n * n) {
res[row][col] = count;
switch(direction) {
case 0:
if (col == right) {
top++;
row++;
direction = 1;
}
else col++;
break;
case 1:
if (row == bot) {
right--;
col--;
direction = 2;
}
else row++;
break;
case 2:
if (col == left) {
bot--;
row--;
direction = 3;
}
else col--;
break;
case 3:
if (row == top) {
left++;
col++;
direction = 0;
}
else row--;
break;
}
}
return res;
}