您的位置:首页 > 其它

[LeetCode] 59. Spiral Matrix II

2016-07-26 18:18 375 查看
思路:

和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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode matrix