您的位置:首页 > 编程语言 > C语言/C++

Leetcode 59. Spiral Matrix II (Medium) (cpp)

2016-07-27 15:08 375 查看
Leetcode 59. Spiral Matrix II (Medium) (cpp)

Tag: Array

Difficulty: Medium

/*

59. Spiral Matrix II (Medium)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n <1) return {};
vector<vector<int>> res(n, vector<int>(n));
int i = n - 1, j = n - 1, k = 1, h = 0, l = 0;
while (k <= n * n) {
for (int col = l; col <= j; col++)
res[h][col] = k++;
if (++h > i) break;
for (int row = h; row <= i; row++)
res[row][j] = k++;
if (--j < l) break;
for (int col = j; col >= l; col--)
res[i][col] = k++;
if (--i < h) break;
for (int row = i; row >= h; row--)
res[row][l] = k++;
if (++l > j) break;
}
return res;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: